home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / feedparser.py < prev    next >
Encoding:
Python Source  |  2007-11-12  |  129.2 KB  |  3,044 lines

  1. #!/usr/bin/env python
  2. """Universal feed parser
  3.  
  4. Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
  5.  
  6. Visit http://feedparser.org/ for the latest version
  7. Visit http://feedparser.org/docs/ for the latest documentation
  8.  
  9. Required: Python 2.1 or later
  10. Recommended: Python 2.3 or later
  11. Recommended: CJKCodecs and iconv_codec <http://cjkpython.i18n.org/>
  12. """
  13.  
  14. __version__ = "4.1"# + "$Revision: 4919 $"[11:15] + "-cvs"
  15. __license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved.
  16.  
  17. Redistribution and use in source and binary forms, with or without modification,
  18. are permitted provided that the following conditions are met:
  19.  
  20. * Redistributions of source code must retain the above copyright notice,
  21.   this list of conditions and the following disclaimer.
  22. * Redistributions in binary form must reproduce the above copyright notice,
  23.   this list of conditions and the following disclaimer in the documentation
  24.   and/or other materials provided with the distribution.
  25.  
  26. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  27. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  28. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  29. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  30. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  31. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  32. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  33. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  34. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  35. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. POSSIBILITY OF SUCH DAMAGE."""
  37. __author__ = "Mark Pilgrim <http://diveintomark.org/>"
  38. __contributors__ = ["Jason Diamond <http://injektilo.org/>",
  39.                     "John Beimler <http://john.beimler.org/>",
  40.                     "Fazal Majid <http://www.majid.info/mylos/weblog/>",
  41.                     "Aaron Swartz <http://aaronsw.com/>",
  42.                     "Kevin Marks <http://epeus.blogspot.com/>"]
  43. _debug = 0
  44.  
  45. # HTTP "User-Agent" header to send to servers when downloading feeds.
  46. # If you are embedding feedparser in a larger application, you should
  47. # change this to your application name and URL.
  48. USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__
  49. import config
  50. import prefs
  51. USER_AGENT += " %s/%s (%s)" % \
  52.     (config.get(prefs.SHORT_APP_NAME),
  53.      config.get(prefs.APP_VERSION),
  54.      config.get(prefs.PROJECT_URL))
  55.  
  56. # HTTP "Accept" header to send to servers when downloading feeds.  If you don't
  57. # want to send an Accept header, set this to None.
  58. ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1"
  59.  
  60. # List of preferred XML parsers, by SAX driver name.  These will be tried first,
  61. # but if they're not installed, Python will keep searching through its own list
  62. # of pre-installed parsers until it finds one that supports everything we need.
  63. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  64.  
  65. # If you want feedparser to automatically run HTML markup through HTML Tidy, set
  66. # this to 1.  Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
  67. # or utidylib <http://utidylib.berlios.de/>.
  68. TIDY_MARKUP = 0
  69.  
  70. # List of Python interfaces for HTML Tidy, in order of preference.  Only useful
  71. # if TIDY_MARKUP = 1
  72. PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
  73.  
  74. # ---------- required modules (should come with any Python distribution) ----------
  75. import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2
  76. try:
  77.     from cStringIO import StringIO as _StringIO
  78. except:
  79.     from StringIO import StringIO as _StringIO
  80.  
  81. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  82.  
  83. # gzip is included with most Python distributions, but may not be available if you compiled your own
  84. try:
  85.     import gzip
  86. except:
  87.     gzip = None
  88. try:
  89.     import zlib
  90. except:
  91.     zlib = None
  92.  
  93. # If a real XML parser is available, feedparser will attempt to use it.  feedparser has
  94. # been tested with the built-in SAX parser, PyXML, and libxml2.  On platforms where the
  95. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  96. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  97. try:
  98.     import xml.sax
  99.     xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  100.     from xml.sax.saxutils import escape as _xmlescape
  101.     _XML_AVAILABLE = 1
  102. except:
  103.     _XML_AVAILABLE = 0
  104.     def _xmlescape(data):
  105.         data = data.replace('&', '&')
  106.         data = data.replace('>', '>')
  107.         data = data.replace('<', '<')
  108.         return data
  109.  
  110. # base64 support for Atom feeds that contain embedded binary data
  111. try:
  112.     import base64, binascii
  113. except:
  114.     base64 = binascii = None
  115.  
  116. # cjkcodecs and iconv_codec provide support for more character encodings.
  117. # Both are available from http://cjkpython.i18n.org/
  118. try:
  119.     import cjkcodecs.aliases
  120. except:
  121.     pass
  122. try:
  123.     import iconv_codec
  124. except:
  125.     pass
  126.  
  127. # chardet library auto-detects character encodings
  128. # Download from http://chardet.feedparser.org/
  129. try:
  130.     import chardet
  131.     if _debug:
  132.         import chardet.constants
  133.         chardet.constants._debug = 1
  134. except:
  135.     chardet = None
  136.  
  137. # ---------- don't touch these ----------
  138. class ThingsNobodyCaresAboutButMe(Exception): pass
  139. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  140. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  141. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  142. class UndeclaredNamespace(Exception): pass
  143.  
  144. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  145. sgmllib.special = re.compile('<!')
  146. sgmllib.charref = re.compile('&#(x?[0-9A-Fa-f]+)[^0-9A-Fa-f]')
  147.  
  148. SUPPORTED_VERSIONS = {'': 'unknown',
  149.                       'rss090': 'RSS 0.90',
  150.                       'rss091n': 'RSS 0.91 (Netscape)',
  151.                       'rss091u': 'RSS 0.91 (Userland)',
  152.                       'rss092': 'RSS 0.92',
  153.                       'rss093': 'RSS 0.93',
  154.                       'rss094': 'RSS 0.94',
  155.                       'rss20': 'RSS 2.0',
  156.                       'rss10': 'RSS 1.0',
  157.                       'rss': 'RSS (unknown version)',
  158.                       'atom01': 'Atom 0.1',
  159.                       'atom02': 'Atom 0.2',
  160.                       'atom03': 'Atom 0.3',
  161.                       'atom10': 'Atom 1.0',
  162.                       'atom': 'Atom (unknown version)',
  163.                       'cdf': 'CDF',
  164.                       'hotrss': 'Hot RSS'
  165.                       }
  166.  
  167. try:
  168.     UserDict = dict
  169. except NameError:
  170.     # Python 2.1 does not have dict
  171.     from UserDict import UserDict
  172.     def dict(aList):
  173.         rc = {}
  174.         for k, v in aList:
  175.             rc[k] = v
  176.         return rc
  177.  
  178. def _entry_equal(a, b):
  179.     if type(a) == list and type(b) == list:
  180.         if len(a) != len(b):
  181.             return False
  182.         for i in xrange (len(a)):
  183.             if not _entry_equal(a[i], b[i]):
  184.                 return False
  185.         return True
  186.     try:
  187.         return a.equal(b)
  188.     except:
  189.         try:
  190.             return b.equal(a)
  191.         except:
  192.             return a == b
  193.  
  194. class FeedParserDict(UserDict):
  195.     keymap = {'channel': 'feed',
  196.               'items': 'entries',
  197.               'guid': 'id',
  198.               'length': 'filesize',
  199.               'image': 'thumbnail',
  200.               'date': 'updated',
  201.               'date_parsed': 'updated_parsed',
  202.               'description': ['subtitle', 'summary'],
  203.               'url': ['href'],
  204.               'modified': 'updated',
  205.               'modified_parsed': 'updated_parsed',
  206.               'issued': 'published',
  207.               'issued_parsed': 'published_parsed',
  208.               'copyright': 'rights',
  209.               'copyright_detail': 'rights_detail',
  210.               'tagline': 'subtitle',
  211.               'tagline_detail': 'subtitle_detail'}
  212.  
  213.     reverse_keymap = {}
  214.     for key in keymap:
  215.         if type (keymap[key]) == types.ListType:
  216.             for k in keymap[key]:
  217.                 reverse_keymap[k] = key
  218.         else:
  219.             reverse_keymap[keymap[key]] = key
  220.  
  221.     def __init__(self, initialData=None):
  222.         if isinstance(initialData, dict):
  223.             UserDict.__init__(self)
  224.             for key in initialData:
  225.                 self[key] = initialData[key]
  226.         elif initialData is not None:
  227.             UserDict.__init__(self, initialData)
  228.         else:
  229.             UserDict.__init__(self)
  230.  
  231.     def reverse_key (self, key):
  232.         if self.reverse_keymap.has_key(key):
  233.             return self.reverse_keymap[key]
  234.         else:
  235.             return key
  236.  
  237.     def get_iter (self):
  238.         class ExtendedIter:
  239.             def __init__ (self, container):
  240.                 self.container = container
  241.                 self.subiter = UserDict.__iter__(container)
  242.             def __iter__ (self):
  243.                 return self
  244.             def next(self):
  245.                 return self.container.reverse_key(self.subiter.next())
  246.         return ExtendedIter (self)
  247.  
  248.     def equal (self, other):
  249.         try:
  250.             iter = other.get_iter()
  251.         except:
  252.             iter = other.__iter__()
  253.         try:
  254.             checked = {}
  255.             for key in iter:
  256.                 if not _entry_equal (self[key], other[key]):
  257.                     return False
  258.                 checked[key] = key
  259.             for key in self.get_iter():
  260.                 if not checked.has_key (key):
  261.                     return False
  262.             return True
  263.         except:
  264.             return False
  265.  
  266.     def __getitem__(self, key):
  267.         if key == 'category':
  268.             return UserDict.__getitem__(self, 'tags')[0]['term']
  269.         if key == 'categories':
  270.             return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
  271.         realkey = self.keymap.get(key, key)
  272.         if type(realkey) == types.ListType:
  273.             for k in realkey:
  274.                 if UserDict.has_key(self, k):
  275.                     return UserDict.__getitem__(self, k)
  276.         if UserDict.has_key(self, key):
  277.             return UserDict.__getitem__(self, key)
  278.         return UserDict.__getitem__(self, realkey)
  279.  
  280.     def __setitem__(self, key, value):
  281.         for k in self.keymap.keys():
  282.             if key == k:
  283.                 key = self.keymap[k]
  284.                 if type(key) == types.ListType:
  285.                     key = key[0]
  286.         return UserDict.__setitem__(self, key, value)
  287.  
  288.     def get(self, key, default=None):
  289.         if self.has_key(key):
  290.             return self[key]
  291.         else:
  292.             return default
  293.  
  294.     def setdefault(self, key, value):
  295.         if not self.has_key(key):
  296.             self[key] = value
  297.         return self[key]
  298.         
  299.     def has_key(self, key):
  300.         try:
  301.             return hasattr(self, key) or UserDict.has_key(self, key)
  302.         except AttributeError:
  303.             return False
  304.         
  305.     def __getattr__(self, key):
  306.         try:
  307.             assert not key.startswith('_')
  308.             return self.__getitem__(key)
  309.         except:
  310.             raise AttributeError, "object has no attribute '%s'" % key
  311.  
  312.     def __setattr__(self, key, value):
  313.         if key.startswith('_') or key == 'data':
  314.             self.__dict__[key] = value
  315.         else:
  316.             return self.__setitem__(key, value)
  317.  
  318.     def __contains__(self, key):
  319.         return self.has_key(key)
  320.  
  321. def zopeCompatibilityHack():
  322.     global FeedParserDict
  323.     del FeedParserDict
  324.     def FeedParserDict(aDict=None):
  325.         rc = {}
  326.         if aDict:
  327.             rc.update(aDict)
  328.         return rc
  329.  
  330. _ebcdic_to_ascii_map = None
  331. def _ebcdic_to_ascii(s):
  332.     global _ebcdic_to_ascii_map
  333.     if not _ebcdic_to_ascii_map:
  334.         emap = (
  335.             0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  336.             16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  337.             128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  338.             144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  339.             32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  340.             38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  341.             45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  342.             186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  343.             195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,201,
  344.             202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
  345.             209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
  346.             216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
  347.             123,65,66,67,68,69,70,71,72,73,232,233,234,235,236,237,
  348.             125,74,75,76,77,78,79,80,81,82,238,239,240,241,242,243,
  349.             92,159,83,84,85,86,87,88,89,90,244,245,246,247,248,249,
  350.             48,49,50,51,52,53,54,55,56,57,250,251,252,253,254,255
  351.             )
  352.         import string
  353.         _ebcdic_to_ascii_map = string.maketrans( \
  354.             ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  355.     return s.translate(_ebcdic_to_ascii_map)
  356.  
  357. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  358. def _urljoin(base, uri):
  359.     uri = _urifixer.sub(r'\1\3', uri)
  360.     return urlparse.urljoin(base, uri)
  361.  
  362. class _FeedParserMixin:
  363.     namespaces = {'': '',
  364.                   'http://backend.userland.com/rss': '',
  365.                   'http://blogs.law.harvard.edu/tech/rss': '',
  366.                   'http://purl.org/rss/1.0/': '',
  367.                   'http://my.netscape.com/rdf/simple/0.9/': '',
  368.                   'http://example.com/newformat#': '',
  369.                   'http://example.com/necho': '',
  370.                   'http://purl.org/echo/': '',
  371.                   'uri/of/echo/namespace#': '',
  372.                   'http://purl.org/pie/': '',
  373.                   'http://purl.org/atom/ns#': '',
  374.                   'http://www.w3.org/2005/Atom': '',
  375.                   'http://purl.org/rss/1.0/modules/rss091#': '',
  376.                   
  377.                   'http://webns.net/mvcb/':                               'admin',
  378.                   'http://purl.org/rss/1.0/modules/aggregation/':         'ag',
  379.                   'http://purl.org/rss/1.0/modules/annotate/':            'annotate',
  380.                   'http://media.tangent.org/rss/1.0/':                    'audio',
  381.                   'http://backend.userland.com/blogChannelModule':        'blogChannel',
  382.                   'http://web.resource.org/cc/':                          'cc',
  383.                   'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  384.                   'http://purl.org/rss/1.0/modules/company':              'co',
  385.                   'http://purl.org/rss/1.0/modules/content/':             'content',
  386.                   'http://my.theinfo.org/changed/1.0/rss/':               'cp',
  387.                   'http://purl.org/dc/elements/1.1/':                     'dc',
  388.                   'http://purl.org/dc/terms/':                            'dcterms',
  389.                   'http://purl.org/rss/1.0/modules/email/':               'email',
  390.                   'http://purl.org/rss/1.0/modules/event/':               'ev',
  391.                   'http://rssnamespace.org/feedburner/ext/1.0':           'feedburner',
  392.                   'http://freshmeat.net/rss/fm/':                         'fm',
  393.                   'http://xmlns.com/foaf/0.1/':                           'foaf',
  394.                   'http://www.w3.org/2003/01/geo/wgs84_pos#':             'geo',
  395.                   'http://postneo.com/icbm/':                             'icbm',
  396.                   'http://purl.org/rss/1.0/modules/image/':               'image',
  397.                   'http://www.itunes.com/DTDs/PodCast-1.0.dtd':           'itunes',
  398.                   'http://example.com/DTDs/PodCast-1.0.dtd':              'itunes',
  399.                   'http://purl.org/rss/1.0/modules/link/':                'l',
  400.                   'http://search.yahoo.com/mrss':                         'media',
  401.                   'http://search.yahoo.com/mrss/':                         'media',
  402.                   'http://docs.yahoo.com/mediaModule':                    'media',
  403.                   'http://tools.search.yahoo.com/mrss/':                  'media',
  404.                   'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  405.                   'http://prismstandard.org/namespaces/1.2/basic/':       'prism',
  406.                   'http://www.w3.org/1999/02/22-rdf-syntax-ns#':          'rdf',
  407.                   'http://www.w3.org/2000/01/rdf-schema#':                'rdfs',
  408.                   'http://purl.org/rss/1.0/modules/reference/':           'ref',
  409.                   'http://purl.org/rss/1.0/modules/richequiv/':           'reqv',
  410.                   'http://purl.org/rss/1.0/modules/search/':              'search',
  411.                   'http://purl.org/rss/1.0/modules/slash/':               'slash',
  412.                   'http://schemas.xmlsoap.org/soap/envelope/':            'soap',
  413.                   'http://purl.org/rss/1.0/modules/servicestatus/':       'ss',
  414.                   'http://hacks.benhammersley.com/rss/streaming/':        'str',
  415.                   'http://purl.org/rss/1.0/modules/subscription/':        'sub',
  416.                   'http://purl.org/rss/1.0/modules/syndication/':         'sy',
  417.                   'http://purl.org/rss/1.0/modules/taxonomy/':            'taxo',
  418.                   'http://purl.org/rss/1.0/modules/threading/':           'thr',
  419.                   'http://purl.org/rss/1.0/modules/textinput/':           'ti',
  420.                   'http://madskills.com/public/xml/rss/module/trackback/':'trackback',
  421.                   'http://wellformedweb.org/commentAPI/':                 'wfw',
  422.                   'http://purl.org/rss/1.0/modules/wiki/':                'wiki',
  423.                   'http://www.w3.org/1999/xhtml':                         'xhtml',
  424.                   'http://www.w3.org/XML/1998/namespace':                 'xml',
  425.                   'http://schemas.pocketsoap.com/rss/myDescModule/':      'szf',
  426.                   "http://participatoryculture.org/RSSModules/dtv/1.0":   'dtv'
  427. }
  428.     _matchnamespaces = {}
  429.  
  430.     can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo']
  431.     can_contain_relative_uris = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  432.     can_contain_dangerous_markup = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  433.     html_types = ['text/html', 'application/xhtml+xml']
  434.     
  435.     def __init__(self, baseuri=None, baselang=None, encoding='utf-8'):
  436.         if _debug: sys.stderr.write('initializing FeedParser\n')
  437.         if not self._matchnamespaces:
  438.             for k, v in self.namespaces.items():
  439.                 self._matchnamespaces[k.lower()] = v
  440.         self.feeddata = FeedParserDict() # feed-level data
  441.         self.encoding = encoding # character encoding
  442.         self.entries = [] # list of entry-level data
  443.         self.version = '' # feed type/version, see SUPPORTED_VERSIONS
  444.         self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  445.  
  446.         # the following are used internally to track state;
  447.         # this is really out of control and should be refactored
  448.         self.infeed = 0
  449.         self.inentry = 0
  450.         self.incontent = 0
  451.         self.intextinput = 0
  452.         self.inimage = 0
  453.         self.inauthor = 0
  454.         self.incontributor = 0
  455.         self.inenclosure = 0
  456.         self.inpublisher = 0
  457.         self.insource = 0
  458.         self.sourcedata = FeedParserDict()
  459.         self.contentparams = FeedParserDict()
  460.         self._summaryKey = None
  461.         self.namespacemap = {}
  462.         self.elementstack = []
  463.         self.basestack = []
  464.         self.langstack = []
  465.         self.baseuri = baseuri or ''
  466.         self.lang = baselang or None
  467.         if baselang:
  468.             self.feeddata['language'] = baselang
  469.  
  470.     def unknown_starttag(self, tag, attrs):
  471.         if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
  472.         # normalize attrs
  473.         attrs = [(k.lower(), v) for k, v in attrs]
  474.         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  475.         
  476.         # track xml:base and xml:lang
  477.         attrsD = FeedParserDict(attrs)
  478.         baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  479.         self.baseuri = _urljoin(self.baseuri, baseuri)
  480.         lang = attrsD.get('xml:lang', attrsD.get('lang'))
  481.         if lang == '':
  482.             # xml:lang could be explicitly set to '', we need to capture that
  483.             lang = None
  484.         elif lang is None:
  485.             # if no xml:lang is specified, use parent lang
  486.             lang = self.lang
  487.         if lang:
  488.             if tag in ('feed', 'rss', 'rdf:RDF'):
  489.                 self.feeddata['language'] = lang
  490.         self.lang = lang
  491.         self.basestack.append(self.baseuri)
  492.         self.langstack.append(lang)
  493.         
  494.         # track namespaces
  495.         for prefix, uri in attrs:
  496.             if prefix.startswith('xmlns:'):
  497.                 self.trackNamespace(prefix[6:], uri)
  498.             elif prefix == 'xmlns':
  499.                 self.trackNamespace(None, uri)
  500.  
  501.         # track inline content
  502.         if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  503.             # element declared itself as escaped markup, but it isn't really
  504.             self.contentparams['type'] = 'application/xhtml+xml'
  505.         if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  506.             # Note: probably shouldn't simply recreate localname here, but
  507.             # our namespace handling isn't actually 100% correct in cases where
  508.             # the feed redefines the default namespace (which is actually
  509.             # the usual case for inline content, thanks Sam), so here we
  510.             # cheat and just reconstruct the element based on localname
  511.             # because that compensates for the bugs in our namespace handling.
  512.             # This will horribly munge inline content with non-empty qnames,
  513.             # but nobody actually does that, so I'm not fixing it.
  514.             tag = tag.split(':')[-1]
  515.             return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0)
  516.  
  517.         # match namespaces
  518.         if tag.find(':') <> -1:
  519.             prefix, suffix = tag.split(':', 1)
  520.         else:
  521.             prefix, suffix = '', tag
  522.         prefix = self.namespacemap.get(prefix, prefix)
  523.         if prefix:
  524.             prefix = prefix + '_'
  525.  
  526.         # special hack for better tracking of empty textinput/image elements in illformed feeds
  527.         if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  528.             self.intextinput = 0
  529.         if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  530.             self.inimage = 0
  531.         
  532.         # call special handler (if defined) or default handler
  533.         methodname = '_start_' + prefix + suffix
  534.         try:
  535.             method = getattr(self, methodname)
  536.             return method(attrsD)
  537.         except AttributeError:
  538.             return self.push(prefix + suffix, 1)
  539.  
  540.     def unknown_endtag(self, tag):
  541.         if _debug: sys.stderr.write('end %s\n' % tag)
  542.         # match namespaces
  543.         if tag.find(':') <> -1:
  544.             prefix, suffix = tag.split(':', 1)
  545.         else:
  546.             prefix, suffix = '', tag
  547.         prefix = self.namespacemap.get(prefix, prefix)
  548.         if prefix:
  549.             prefix = prefix + '_'
  550.  
  551.         # call special handler (if defined) or default handler
  552.         methodname = '_end_' + prefix + suffix
  553.         try:
  554.             method = getattr(self, methodname)
  555.             method()
  556.         except AttributeError:
  557.             self.pop(prefix + suffix)
  558.  
  559.         # track inline content
  560.         if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  561.             # element declared itself as escaped markup, but it isn't really
  562.             self.contentparams['type'] = 'application/xhtml+xml'
  563.         if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  564.             tag = tag.split(':')[-1]
  565.             self.handle_data('</%s>' % tag, escape=0)
  566.  
  567.         # track xml:base and xml:lang going out of scope
  568.         if self.basestack:
  569.             self.basestack.pop()
  570.             if self.basestack and self.basestack[-1]:
  571.                 self.baseuri = self.basestack[-1]
  572.         if self.langstack:
  573.             self.langstack.pop()
  574.             if self.langstack: # and (self.langstack[-1] is not None):
  575.                 self.lang = self.langstack[-1]
  576.  
  577.     def handle_charref(self, ref):
  578.         # called for each character reference, e.g. for ' ', ref will be '160'
  579.         if not self.elementstack: return
  580.         ref = ref.lower()
  581.         if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  582.             text = '&#%s;' % ref
  583.         else:
  584.             if ref[0] == 'x':
  585.                 c = int(ref[1:], 16)
  586.             else:
  587.                 c = int(ref)
  588.             text = unichr(c).encode('utf-8')
  589.         self.elementstack[-1][2].append(text)
  590.  
  591.     def handle_entityref(self, ref):
  592.         # called for each entity reference, e.g. for '©', ref will be 'copy'
  593.         if not self.elementstack: return
  594.         if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref)
  595.         if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  596.             text = '&%s;' % ref
  597.         else:
  598.             # entity resolution graciously donated by Aaron Swartz
  599.             def name2cp(k):
  600.                 import htmlentitydefs
  601.                 if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3
  602.                     return htmlentitydefs.name2codepoint[k]
  603.                 k = htmlentitydefs.entitydefs[k]
  604.                 if k.startswith('&#') and k.endswith(';'):
  605.                     return int(k[2:-1]) # not in latin-1
  606.                 return ord(k)
  607.             try: name2cp(ref)
  608.             except KeyError: text = '&%s;' % ref
  609.             else: text = unichr(name2cp(ref)).encode('utf-8')
  610.         self.elementstack[-1][2].append(text)
  611.  
  612.     def handle_data(self, text, escape=1):
  613.         # called for each block of plain text, i.e. outside of any tag and
  614.         # not containing any character or entity references
  615.         if not self.elementstack: return
  616.         if escape and self.contentparams.get('type') == 'application/xhtml+xml':
  617.             text = _xmlescape(text)
  618.         self.elementstack[-1][2].append(text)
  619.  
  620.     def handle_comment(self, text):
  621.         # called for each comment, e.g. <!-- insert message here -->
  622.         pass
  623.  
  624.     def handle_pi(self, text):
  625.         # called for each processing instruction, e.g. <?instruction>
  626.         pass
  627.  
  628.     def handle_decl(self, text):
  629.         pass
  630.  
  631.     def parse_declaration(self, i):
  632.         # override internal declaration handler to handle CDATA blocks
  633.         if _debug: sys.stderr.write('entering parse_declaration\n')
  634.         if self.rawdata[i:i+9] == '<![CDATA[':
  635.             k = self.rawdata.find(']]>', i)
  636.             if k == -1: k = len(self.rawdata)
  637.             self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  638.             return k+3
  639.         else:
  640.             k = self.rawdata.find('>', i)
  641.             return k+1
  642.  
  643.     def mapContentType(self, contentType):
  644.         contentType = contentType.lower()
  645.         if contentType == 'text':
  646.             contentType = 'text/plain'
  647.         elif contentType == 'html':
  648.             contentType = 'text/html'
  649.         elif contentType == 'xhtml':
  650.             contentType = 'application/xhtml+xml'
  651.         return contentType
  652.     
  653.     def trackNamespace(self, prefix, uri):
  654.         loweruri = uri.lower()
  655.         if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
  656.             self.version = 'rss090'
  657.         if loweruri == 'http://purl.org/rss/1.0/' and not self.version:
  658.             self.version = 'rss10'
  659.         if loweruri == 'http://www.w3.org/2005/atom' and not self.version:
  660.             self.version = 'atom10'
  661.         if loweruri.find('backend.userland.com/rss') <> -1:
  662.             # match any backend.userland.com namespace
  663.             uri = 'http://backend.userland.com/rss'
  664.             loweruri = uri
  665.         if self._matchnamespaces.has_key(loweruri):
  666.             self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  667.             self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  668.         else:
  669.             self.namespacesInUse[prefix or ''] = uri
  670.  
  671.     def resolveURI(self, uri):
  672.         return _urljoin(self.baseuri or '', uri)
  673.     
  674.     def decodeEntities(self, element, data):
  675.         return data
  676.  
  677.     def push(self, element, expectingText):
  678.         self.elementstack.append([element, expectingText, []])
  679.  
  680.     def pop(self, element, stripWhitespace=1):
  681.         if not self.elementstack: return
  682.         if self.elementstack[-1][0] != element: return
  683.         
  684.         element, expectingText, pieces = self.elementstack.pop()
  685.         output = ''.join(pieces)
  686.         if stripWhitespace:
  687.             output = output.strip()
  688.         if not expectingText: return output
  689.  
  690.         # decode base64 content
  691.         if base64 and self.contentparams.get('base64', 0):
  692.             try:
  693.                 output = base64.decodestring(output)
  694.             except binascii.Error:
  695.                 pass
  696.             except binascii.Incomplete:
  697.                 pass
  698.                 
  699.         # resolve relative URIs
  700.         if (element in self.can_be_relative_uri) and output:
  701.             output = self.resolveURI(output)
  702.         
  703.         # decode entities within embedded markup
  704.         if not self.contentparams.get('base64', 0):
  705.             output = self.decodeEntities(element, output)
  706.  
  707.         # remove temporary cruft from contentparams
  708.         try:
  709.             del self.contentparams['mode']
  710.         except KeyError:
  711.             pass
  712.         try:
  713.             del self.contentparams['base64']
  714.         except KeyError:
  715.             pass
  716.  
  717.         # resolve relative URIs within embedded markup
  718.         if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  719.             if element in self.can_contain_relative_uris:
  720.                 output = _resolveRelativeURIs(output, self.baseuri, self.encoding)
  721.         
  722.         # sanitize embedded markup
  723.         if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  724.             if element in self.can_contain_dangerous_markup:
  725.                 output = sanitizeHTML(output, self.encoding)
  726.  
  727.         if self.encoding and type(output) != type(u''):
  728.             try:
  729.                 output = unicode(output, self.encoding)
  730.             except:
  731.                 pass
  732.  
  733.         # categories/tags/keywords/whatever are handled in _end_category
  734.         if element == 'category':
  735.             return output
  736.         
  737.         # store output in appropriate place(s)
  738.         if self.inentry and not self.insource:
  739.             if element == 'content':
  740.                 self.entries[-1].setdefault(element, [])
  741.                 contentparams = copy.deepcopy(self.contentparams)
  742.                 contentparams['value'] = output
  743.                 self.entries[-1][element].append(contentparams)
  744.             elif element == 'link':
  745.                 self.entries[-1][element] = output
  746.                 if output:
  747.                     self.entries[-1]['links'][-1]['href'] = output
  748.             else:
  749.                 if element == 'description':
  750.                     element = 'summary'
  751.                 self.entries[-1][element] = output
  752.                 if self.incontent:
  753.                     contentparams = copy.deepcopy(self.contentparams)
  754.                     contentparams['value'] = output
  755.                     self.entries[-1][element + '_detail'] = contentparams
  756.         elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage):
  757.             context = self._getContext()
  758.             if element == 'description':
  759.                 element = 'subtitle'
  760.             context[element] = output
  761.             if element == 'link':
  762.                 context['links'][-1]['href'] = output
  763.             elif self.incontent:
  764.                 contentparams = copy.deepcopy(self.contentparams)
  765.                 contentparams['value'] = output
  766.                 context[element + '_detail'] = contentparams
  767.         return output
  768.  
  769.     def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  770.         self.incontent += 1
  771.         self.contentparams = FeedParserDict({
  772.             'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  773.             'language': self.lang,
  774.             'base': self.baseuri})
  775.         self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  776.         self.push(tag, expectingText)
  777.  
  778.     def popContent(self, tag):
  779.         value = self.pop(tag)
  780.         self.incontent -= 1
  781.         self.contentparams.clear()
  782.         return value
  783.         
  784.     def _mapToStandardPrefix(self, name):
  785.         colonpos = name.find(':')
  786.         if colonpos <> -1:
  787.             prefix = name[:colonpos]
  788.             suffix = name[colonpos+1:]
  789.             prefix = self.namespacemap.get(prefix, prefix)
  790.             name = prefix + ':' + suffix
  791.         return name
  792.         
  793.     def _getAttribute(self, attrsD, name):
  794.         return attrsD.get(self._mapToStandardPrefix(name))
  795.  
  796.     def _isBase64(self, attrsD, contentparams):
  797.         if attrsD.get('mode', '') == 'base64':
  798.             return 1
  799.         # We should never assume text is base64 --NN
  800.         else:
  801.             return 0
  802.         if self.contentparams['type'].startswith('text/'):
  803.             return 0
  804.         if self.contentparams['type'].endswith('+xml'):
  805.             return 0
  806.         if self.contentparams['type'].endswith('/xml'):
  807.             return 0
  808.         return 1
  809.  
  810.     def _itsAnHrefDamnIt(self, attrsD):
  811.         href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  812.         if href:
  813.             try:
  814.                 del attrsD['url']
  815.             except KeyError:
  816.                 pass
  817.             try:
  818.                 del attrsD['uri']
  819.             except KeyError:
  820.                 pass
  821.             attrsD['href'] = href
  822.         return attrsD
  823.     
  824.     def _save(self, key, value):
  825.         context = self._getContext()
  826.         context.setdefault(key, value)
  827.  
  828.     def _start_rss(self, attrsD):
  829.         versionmap = {'0.91': 'rss091u',
  830.                       '0.92': 'rss092',
  831.                       '0.93': 'rss093',
  832.                       '0.94': 'rss094'}
  833.         if not self.version:
  834.             attr_version = attrsD.get('version', '')
  835.             version = versionmap.get(attr_version)
  836.             if version:
  837.                 self.version = version
  838.             elif attr_version.startswith('2.'):
  839.                 self.version = 'rss20'
  840.             else:
  841.                 self.version = 'rss'
  842.     
  843.     def _start_dlhottitles(self, attrsD):
  844.         self.version = 'hotrss'
  845.  
  846.     def _start_channel(self, attrsD):
  847.         self.infeed = 1
  848.         self._cdf_common(attrsD)
  849.     _start_feedinfo = _start_channel
  850.  
  851.     def _cdf_common(self, attrsD):
  852.         if attrsD.has_key('lastmod'):
  853.             self._start_modified({})
  854.             self.elementstack[-1][-1] = attrsD['lastmod']
  855.             self._end_modified()
  856.         if attrsD.has_key('href'):
  857.             self._start_link({})
  858.             self.elementstack[-1][-1] = attrsD['href']
  859.             self._end_link()
  860.     
  861.     def _start_feed(self, attrsD):
  862.         self.infeed = 1
  863.         versionmap = {'0.1': 'atom01',
  864.                       '0.2': 'atom02',
  865.                       '0.3': 'atom03'}
  866.         if not self.version:
  867.             attr_version = attrsD.get('version')
  868.             version = versionmap.get(attr_version)
  869.             if version:
  870.                 self.version = version
  871.             else:
  872.                 self.version = 'atom'
  873.  
  874.     def _end_channel(self):
  875.         self.infeed = 0
  876.     _end_feed = _end_channel
  877.     
  878.     def _start_image(self, attrsD):
  879.         self.inimage = 1
  880.         self.push('image', 0)
  881.         context = self._getContext()
  882.         context.setdefault('image', FeedParserDict())
  883.             
  884.     def _end_image(self):
  885.         self.pop('image')
  886.         self.inimage = 0
  887.  
  888.     def _start_textinput(self, attrsD):
  889.         self.intextinput = 1
  890.         self.push('textinput', 0)
  891.         context = self._getContext()
  892.         context.setdefault('textinput', FeedParserDict())
  893.     _start_textInput = _start_textinput
  894.     
  895.     def _end_textinput(self):
  896.         self.pop('textinput')
  897.         self.intextinput = 0
  898.     _end_textInput = _end_textinput
  899.  
  900.     def _start_author(self, attrsD):
  901.         self.inauthor = 1
  902.         self.push('author', 1)
  903.     _start_managingeditor = _start_author
  904.     _start_dc_author = _start_author
  905.     _start_dc_creator = _start_author
  906.     _start_itunes_author = _start_author
  907.  
  908.     def _end_author(self):
  909.         self.pop('author')
  910.         self.inauthor = 0
  911.         self._sync_author_detail()
  912.     _end_managingeditor = _end_author
  913.     _end_dc_author = _end_author
  914.     _end_dc_creator = _end_author
  915.     _end_itunes_author = _end_author
  916.  
  917.     def _start_itunes_owner(self, attrsD):
  918.         self.inpublisher = 1
  919.         self.push('publisher', 0)
  920.  
  921.     def _end_itunes_owner(self):
  922.         self.pop('publisher')
  923.         self.inpublisher = 0
  924.         self._sync_author_detail('publisher')
  925.  
  926.     def _start_contributor(self, attrsD):
  927.         self.incontributor = 1
  928.         context = self._getContext()
  929.         context.setdefault('contributors', [])
  930.         context['contributors'].append(FeedParserDict())
  931.         self.push('contributor', 0)
  932.  
  933.     def _end_contributor(self):
  934.         self.pop('contributor')
  935.         self.incontributor = 0
  936.  
  937.     def _start_dc_contributor(self, attrsD):
  938.         self.incontributor = 1
  939.         context = self._getContext()
  940.         context.setdefault('contributors', [])
  941.         context['contributors'].append(FeedParserDict())
  942.         self.push('name', 0)
  943.  
  944.     def _end_dc_contributor(self):
  945.         self._end_name()
  946.         self.incontributor = 0
  947.  
  948.     def _start_name(self, attrsD):
  949.         self.push('name', 0)
  950.     _start_itunes_name = _start_name
  951.  
  952.     def _end_name(self):
  953.         value = self.pop('name')
  954.         if self.inpublisher:
  955.             self._save_author('name', value, 'publisher')
  956.         elif self.inauthor:
  957.             self._save_author('name', value)
  958.         elif self.incontributor:
  959.             self._save_contributor('name', value)
  960.         elif self.intextinput:
  961.             context = self._getContext()
  962.             context['textinput']['name'] = value
  963.     _end_itunes_name = _end_name
  964.  
  965.     def _start_width(self, attrsD):
  966.         self.push('width', 0)
  967.  
  968.     def _end_width(self):
  969.         value = self.pop('width')
  970.         try:
  971.             value = int(value)
  972.         except:
  973.             value = 0
  974.         if self.inimage:
  975.             context = self._getContext()
  976.             context['image']['width'] = value
  977.  
  978.     def _start_height(self, attrsD):
  979.         self.push('height', 0)
  980.  
  981.     def _end_height(self):
  982.         value = self.pop('height')
  983.         try:
  984.             value = int(value)
  985.         except:
  986.             value = 0
  987.         if self.inimage:
  988.             context = self._getContext()
  989.             context['image']['height'] = value
  990.  
  991.     def _start_url(self, attrsD):
  992.         self.push('href', 1)
  993.     _start_homepage = _start_url
  994.     _start_uri = _start_url
  995.  
  996.     def _end_url(self):
  997.         value = self.pop('href')
  998.         if self.inauthor:
  999.             self._save_author('href', value)
  1000.         elif self.incontributor:
  1001.             self._save_contributor('href', value)
  1002.         elif self.inimage:
  1003.             context = self._getContext()
  1004.             context['image']['href'] = value
  1005.         elif self.intextinput:
  1006.             context = self._getContext()
  1007.             context['textinput']['link'] = value
  1008.     _end_homepage = _end_url
  1009.     _end_uri = _end_url
  1010.  
  1011.     def _start_email(self, attrsD):
  1012.         self.push('email', 0)
  1013.     _start_itunes_email = _start_email
  1014.  
  1015.     def _end_email(self):
  1016.         value = self.pop('email')
  1017.         if self.inpublisher:
  1018.             self._save_author('email', value, 'publisher')
  1019.         elif self.inauthor:
  1020.             self._save_author('email', value)
  1021.         elif self.incontributor:
  1022.             self._save_contributor('email', value)
  1023.     _end_itunes_email = _end_email
  1024.  
  1025.     def _getContext(self):
  1026.         if self.insource:
  1027.             context = self.sourcedata
  1028.         elif self.inentry:
  1029.             context = self.entries[-1]
  1030.         else:
  1031.             context = self.feeddata
  1032.         return context
  1033.  
  1034.     def _save_author(self, key, value, prefix='author'):
  1035.         context = self._getContext()
  1036.         context.setdefault(prefix + '_detail', FeedParserDict())
  1037.         context[prefix + '_detail'][key] = value
  1038.         self._sync_author_detail()
  1039.  
  1040.     def _save_contributor(self, key, value):
  1041.         context = self._getContext()
  1042.         context.setdefault('contributors', [FeedParserDict()])
  1043.         context['contributors'][-1][key] = value
  1044.  
  1045.     def _sync_author_detail(self, key='author'):
  1046.         context = self._getContext()
  1047.         detail = context.get('%s_detail' % key)
  1048.         if detail:
  1049.             name = detail.get('name')
  1050.             email = detail.get('email')
  1051.             if name and email:
  1052.                 context[key] = '%s (%s)' % (name, email)
  1053.             elif name:
  1054.                 context[key] = name
  1055.             elif email:
  1056.                 context[key] = email
  1057.         else:
  1058.             author = context.get(key)
  1059.             if not author: return
  1060.             emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''', author)
  1061.             if not emailmatch: return
  1062.             email = emailmatch.group(0)
  1063.             # probably a better way to do the following, but it passes all the tests
  1064.             author = author.replace(email, '')
  1065.             author = author.replace('()', '')
  1066.             author = author.strip()
  1067.             if author and (author[0] == '('):
  1068.                 author = author[1:]
  1069.             if author and (author[-1] == ')'):
  1070.                 author = author[:-1]
  1071.             author = author.strip()
  1072.             context.setdefault('%s_detail' % key, FeedParserDict())
  1073.             context['%s_detail' % key]['name'] = author
  1074.             context['%s_detail' % key]['email'] = email
  1075.  
  1076.     def _start_subtitle(self, attrsD):
  1077.         self.pushContent('subtitle', attrsD, 'text/plain', 1)
  1078.     _start_tagline = _start_subtitle
  1079.     _start_itunes_subtitle = _start_subtitle
  1080.  
  1081.     def _end_subtitle(self):
  1082.         self.popContent('subtitle')
  1083.     _end_tagline = _end_subtitle
  1084.     _end_itunes_subtitle = _end_subtitle
  1085.             
  1086.     def _start_rights(self, attrsD):
  1087.         self.pushContent('rights', attrsD, 'text/plain', 1)
  1088.     _start_dc_rights = _start_rights
  1089.     _start_copyright = _start_rights
  1090.  
  1091.     def _end_rights(self):
  1092.         self.popContent('rights')
  1093.     _end_dc_rights = _end_rights
  1094.     _end_copyright = _end_rights
  1095.  
  1096.     def _start_item(self, attrsD):
  1097.         self.entries.append(FeedParserDict())
  1098.         self.push('item', 0)
  1099.         self.inentry = 1
  1100.         self.guidislink = 0
  1101.         id = self._getAttribute(attrsD, 'rdf:about')
  1102.         if id:
  1103.             context = self._getContext()
  1104.             context['id'] = id
  1105.         self._cdf_common(attrsD)
  1106.     _start_entry = _start_item
  1107.     _start_product = _start_item
  1108.  
  1109.     def _end_item(self):
  1110.         self.pop('item')
  1111.         self.inentry = 0
  1112.     _end_entry = _end_item
  1113.  
  1114.     def _start_dc_language(self, attrsD):
  1115.         self.push('language', 1)
  1116.     _start_language = _start_dc_language
  1117.  
  1118.     def _end_dc_language(self):
  1119.         self.lang = self.pop('language')
  1120.     _end_language = _end_dc_language
  1121.  
  1122.     def _start_dc_publisher(self, attrsD):
  1123.         self.push('publisher', 1)
  1124.     _start_webmaster = _start_dc_publisher
  1125.  
  1126.     def _end_dc_publisher(self):
  1127.         self.pop('publisher')
  1128.         self._sync_author_detail('publisher')
  1129.     _end_webmaster = _end_dc_publisher
  1130.  
  1131.     def _start_published(self, attrsD):
  1132.         self.push('published', 1)
  1133.     _start_dcterms_issued = _start_published
  1134.     _start_issued = _start_published
  1135.  
  1136.     def _end_published(self):
  1137.         value = self.pop('published')
  1138.         self._save('published_parsed', _parse_date(value))
  1139.     _end_dcterms_issued = _end_published
  1140.     _end_issued = _end_published
  1141.  
  1142.     def _start_updated(self, attrsD):
  1143.         self.push('updated', 1)
  1144.     _start_modified = _start_updated
  1145.     _start_dcterms_modified = _start_updated
  1146.     _start_pubdate = _start_updated
  1147.     _start_dc_date = _start_updated
  1148.  
  1149.     def _end_updated(self):
  1150.         value = self.pop('updated')
  1151.         parsed_value = _parse_date(value)
  1152.         self._save('updated_parsed', parsed_value)
  1153.     _end_modified = _end_updated
  1154.     _end_dcterms_modified = _end_updated
  1155.     _end_pubdate = _end_updated
  1156.     _end_dc_date = _end_updated
  1157.  
  1158.     def _start_created(self, attrsD):
  1159.         self.push('created', 1)
  1160.     _start_dcterms_created = _start_created
  1161.  
  1162.     def _end_created(self):
  1163.         value = self.pop('created')
  1164.         self._save('created_parsed', _parse_date(value))
  1165.     _end_dcterms_created = _end_created
  1166.  
  1167.     def _start_expirationdate(self, attrsD):
  1168.         self.push('expired', 1)
  1169.  
  1170.     def _end_expirationdate(self):
  1171.         self._save('expired_parsed', _parse_date(self.pop('expired')))
  1172.  
  1173.     def _start_cc_license(self, attrsD):
  1174.         self.push('license', 1)
  1175.         value = self._getAttribute(attrsD, 'rdf:resource')
  1176.         if value:
  1177.             self.elementstack[-1][2].append(value)
  1178.         self.pop('license')
  1179.         
  1180.     def _start_creativecommons_license(self, attrsD):
  1181.         self.push('license', 1)
  1182.  
  1183.     def _end_creativecommons_license(self):
  1184.         self.pop('license')
  1185.  
  1186.     def _addTag(self, term, scheme, label):
  1187.         context = self._getContext()
  1188.         tags = context.setdefault('tags', [])
  1189.         if (not term) and (not scheme) and (not label): return
  1190.         value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  1191.         if value not in tags:
  1192.             tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label}))
  1193.  
  1194.     def _start_category(self, attrsD):
  1195.         if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD))
  1196.         term = attrsD.get('term')
  1197.         scheme = attrsD.get('scheme', attrsD.get('domain'))
  1198.         label = attrsD.get('label')
  1199.         self._addTag(term, scheme, label)
  1200.         self.push('category', 1)
  1201.     _start_dc_subject = _start_category
  1202.     _start_keywords = _start_category
  1203.     _start_media_category = _start_category
  1204.         
  1205.     def _end_itunes_keywords(self):
  1206.         for term in self.pop('itunes_keywords').split():
  1207.             self._addTag(term, 'http://www.itunes.com/', None)
  1208.         
  1209.     def _start_itunes_category(self, attrsD):
  1210.         self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
  1211.         self.push('category', 1)
  1212.         
  1213.     def _end_category(self):
  1214.         value = self.pop('category')
  1215.         if not value: return
  1216.         context = self._getContext()
  1217.         tags = context['tags']
  1218.         if value and len(tags) and not tags[-1]['term']:
  1219.             tags[-1]['term'] = value
  1220.         else:
  1221.             self._addTag(value, None, None)
  1222.     _end_dc_subject = _end_category
  1223.     _end_keywords = _end_category
  1224.     _end_itunes_category = _end_category
  1225.     _end_media_category = _end_category
  1226.  
  1227.     def _start_cloud(self, attrsD):
  1228.         self._getContext()['cloud'] = FeedParserDict(attrsD)
  1229.         
  1230.     def _start_link(self, attrsD):
  1231.         attrsD.setdefault('rel', 'alternate')
  1232.         attrsD.setdefault('type', 'text/html')
  1233.         attrsD = self._itsAnHrefDamnIt(attrsD)
  1234.         if attrsD.has_key('href'):
  1235.             attrsD['href'] = self.resolveURI(attrsD['href'])
  1236.         expectingText = self.infeed or self.inentry or self.insource
  1237.         context = self._getContext()
  1238.         context.setdefault('links', [])
  1239.         context['links'].append(FeedParserDict(attrsD))
  1240.         if attrsD['rel'] == 'enclosure':
  1241.             self._start_enclosure(attrsD)
  1242.         if attrsD.has_key('href'):
  1243.             expectingText = 0
  1244.             if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1245.                 context['link'] = attrsD['href']
  1246.         else:
  1247.             self.push('link', expectingText)
  1248.     _start_producturl = _start_link
  1249.  
  1250.     def _end_link(self):
  1251.         value = self.pop('link')
  1252.         context = self._getContext()
  1253.         if self.intextinput:
  1254.             context['textinput']['link'] = value
  1255.         if self.inimage:
  1256.             context['image']['link'] = value
  1257.     _end_producturl = _end_link
  1258.  
  1259.     def _start_guid(self, attrsD):
  1260.         self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1261.         self.push('id', 1)
  1262.  
  1263.     def _end_guid(self):
  1264.         value = self.pop('id')
  1265.         self._save('guidislink', self.guidislink and not self._getContext().has_key('link'))
  1266.         if self.guidislink:
  1267.             # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1268.             # and only if the item doesn't already have a link element
  1269.             self._save('link', value)
  1270.  
  1271.     def _start_title(self, attrsD):
  1272.         self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1273.     _start_dc_title = _start_title
  1274.     _start_media_title = _start_title
  1275.  
  1276.     def _end_title(self):
  1277.         value = self.popContent('title')
  1278.         context = self._getContext()
  1279.         if self.intextinput:
  1280.             context['textinput']['title'] = value
  1281.         elif self.inimage:
  1282.             context['image']['title'] = value
  1283.     _end_dc_title = _end_title
  1284.     _end_media_title = _end_title
  1285.  
  1286.     def _start_description(self, attrsD):
  1287.         context = self._getContext()
  1288.         if context.has_key('summary'):
  1289.             self._summaryKey = 'content'
  1290.             self._start_content(attrsD)
  1291.         else:
  1292.             self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
  1293.  
  1294.     def _start_abstract(self, attrsD):
  1295.         self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1296.  
  1297.     def _end_description(self):
  1298.         if self._summaryKey == 'content':
  1299.             self._end_content()
  1300.         else:
  1301.             value = self.popContent('description')
  1302.             context = self._getContext()
  1303.             if self.intextinput:
  1304.                 context['textinput']['description'] = value
  1305.             elif self.inimage:
  1306.                 context['image']['description'] = value
  1307.         self._summaryKey = None
  1308.     _end_abstract = _end_description
  1309.  
  1310.     def _start_info(self, attrsD):
  1311.         self.pushContent('info', attrsD, 'text/plain', 1)
  1312.     _start_feedburner_browserfriendly = _start_info
  1313.  
  1314.     def _end_info(self):
  1315.         self.popContent('info')
  1316.     _end_feedburner_browserfriendly = _end_info
  1317.  
  1318.     def _start_generator(self, attrsD):
  1319.         if attrsD:
  1320.             attrsD = self._itsAnHrefDamnIt(attrsD)
  1321.             if attrsD.has_key('href'):
  1322.                 attrsD['href'] = self.resolveURI(attrsD['href'])
  1323.         self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1324.         self.push('generator', 1)
  1325.  
  1326.     def _end_generator(self):
  1327.         value = self.pop('generator')
  1328.         context = self._getContext()
  1329.         if context.has_key('generator_detail'):
  1330.             context['generator_detail']['name'] = value
  1331.             
  1332.     def _start_admin_generatoragent(self, attrsD):
  1333.         self.push('generator', 1)
  1334.         value = self._getAttribute(attrsD, 'rdf:resource')
  1335.         if value:
  1336.             self.elementstack[-1][2].append(value)
  1337.         self.pop('generator')
  1338.         self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1339.  
  1340.     def _start_admin_errorreportsto(self, attrsD):
  1341.         self.push('errorreportsto', 1)
  1342.         value = self._getAttribute(attrsD, 'rdf:resource')
  1343.         if value:
  1344.             self.elementstack[-1][2].append(value)
  1345.         self.pop('errorreportsto')
  1346.         
  1347.     def _start_summary(self, attrsD):
  1348.         context = self._getContext()
  1349.         if context.has_key('summary'):
  1350.             self._summaryKey = 'content'
  1351.             self._start_content(attrsD)
  1352.         else:
  1353.             self._summaryKey = 'summary'
  1354.             self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)
  1355.     _start_itunes_summary = _start_summary
  1356.  
  1357.     def _end_summary(self):
  1358.         if self._summaryKey == 'content':
  1359.             self._end_content()
  1360.         else:
  1361.             self.popContent(self._summaryKey or 'summary')
  1362.         self._summaryKey = None
  1363.     _end_itunes_summary = _end_summary
  1364.         
  1365.     def _start_enclosure(self, attrsD):
  1366.         self.inenclosure += 1
  1367.         attrsD = self._itsAnHrefDamnIt(attrsD)
  1368.         self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD))
  1369.         href = attrsD.get('href')
  1370.         if href:
  1371.             context = self._getContext()
  1372.             if not context.get('id'):
  1373.                 context['id'] = href
  1374.     _start_media_content = _start_enclosure
  1375.  
  1376.     def _end_enclosure(self):
  1377.         self.inenclosure -= 1
  1378.     _end_media_content = _end_enclosure
  1379.  
  1380.     def _start_media_thumbnail(self,attrsD):
  1381.         self.push('media:thumbnail',1)
  1382.         if self.inentry:
  1383.             if self.inenclosure:
  1384.                 self.entries[-1]['enclosures'][-1]['thumbnail']=FeedParserDict(attrsD)
  1385.             else:
  1386.                 self.entries[-1]['thumbnail'] = FeedParserDict(attrsD)
  1387.  
  1388.     def _end_media_thumbnail(self):
  1389.         self.pop('media:thumbnail')
  1390.         
  1391.     def _start_media_text(self,attrsD):
  1392.         self.push('media:text',1)
  1393.  
  1394.     def _end_media_text(self):
  1395.         value = self.pop('media:text')
  1396.         if self.inentry:
  1397.             if self.inenclosure:
  1398.                 self.entries[-1]['enclosures'][-1]['text'] = value
  1399.             else:
  1400.                 self.entries[-1]['text'] = value
  1401.  
  1402.     def _start_media_people(self,attrsD):
  1403.         self.push('media:people',1)
  1404.         try:
  1405.             self.peoplerole = attrsD['role']
  1406.         except:
  1407.             self.peoplerole = 'unknown'
  1408.  
  1409.     def _end_media_people(self):
  1410.         value = self.pop('media:people').split('|')
  1411.         if self.inentry:
  1412.             if self.inenclosure:
  1413.                 self.entries[-1]['enclosures'][-1].setdefault('roles', {})
  1414.                 self.entries[-1]['enclosures'][-1].roles[self.peoplerole]=value
  1415.             else:
  1416.                 self.entries[-1].setdefault('roles', {})
  1417.                 self.entries[-1].roles[self.peoplerole]=value
  1418.  
  1419.     def _start_dtv_startnback(self,attrsD):
  1420.         self.push('dtv:startnback',1)        
  1421.  
  1422.     def _end_dtv_startnback(self):
  1423.         self.feeddata['startnback'] = self.pop('dtv:startnback')
  1424.  
  1425.     def _start_dtv_librarylink(self,attrsD):
  1426.         self.push('dtv:librarylink',1)        
  1427.  
  1428.     def _end_dtv_librarylink(self):
  1429.         self.feeddata['librarylink'] = self.pop('dtv:librarylink')
  1430.  
  1431.     def _start_dtv_releasedate(self,attrsD):
  1432.         self.push('dtv:releasedate',1)        
  1433.  
  1434.     def _end_dtv_releasedate(self):
  1435.         value = self.pop('dtv:releasedate')
  1436.         if self.inentry:
  1437.             if self.inenclosure:
  1438.                 self.entries[-1]['enclosures'][-1]['releasedate'] = value
  1439.                 self.entries[-1]['enclosures'][-1]['releasedate_parsed'] = _parse_date(value)
  1440.             else:
  1441.                 self.entries[-1]['releasedate'] = value
  1442.                 self.entries[-1]['releasedate_parsed'] = _parse_date(value)
  1443.         
  1444.     def _start_dtv_paymentlink(self,attrsD):
  1445.         self.incontent += 1
  1446.         self.contentparams['mode'] = 'xml'
  1447.         self.contentparams['type'] = 'application/xhtml+xml'
  1448.         self.push('dtv:paymentlink',1)
  1449.         if self.inentry:
  1450.             if attrsD.has_key('url'):
  1451.                 if self.inenclosure:
  1452.                     self.entries[-1]['enclosures'][-1]['payment_url'] = attrsD['url']
  1453.                 else:
  1454.                     self.entries[-1]['payment_url'] = attrsD['url']
  1455.  
  1456.     def _end_dtv_paymentlink(self):
  1457.         value = sanitizeHTML(self.pop('dtv:paymentlink'),self.encoding)
  1458.         self.incontent -= 1
  1459.         self.contentparams.clear()
  1460.         if self.inentry:
  1461.             if self.inenclosure:
  1462.                 self.entries[-1]['enclosures'][-1]['payment_html'] = value
  1463.             else:
  1464.                 self.entries[-1]['payment_html'] = value
  1465.  
  1466.     def _start_source(self, attrsD):
  1467.         self.insource = 1
  1468.  
  1469.     def _end_source(self):
  1470.         self.insource = 0
  1471.         self._getContext()['source'] = copy.deepcopy(self.sourcedata)
  1472.         self.sourcedata.clear()
  1473.  
  1474.     def _start_content(self, attrsD):
  1475.         self.pushContent('content', attrsD, 'text/plain', 1)
  1476.         src = attrsD.get('src')
  1477.         if src:
  1478.             self.contentparams['src'] = src
  1479.         self.push('content', 1)
  1480.  
  1481.     def _start_prodlink(self, attrsD):
  1482.         self.pushContent('content', attrsD, 'text/html', 1)
  1483.  
  1484.     def _start_body(self, attrsD):
  1485.         self.pushContent('content', attrsD, 'application/xhtml+xml', 1)
  1486.     _start_xhtml_body = _start_body
  1487.  
  1488.     def _start_content_encoded(self, attrsD):
  1489.         self.pushContent('content', attrsD, 'text/html', 1)
  1490.     _start_fullitem = _start_content_encoded
  1491.  
  1492.     def _end_content(self):
  1493.         copyToDescription = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types)
  1494.         value = self.popContent('content')
  1495.         if copyToDescription:
  1496.             self._save('description', value)
  1497.     _end_body = _end_content
  1498.     _end_xhtml_body = _end_content
  1499.     _end_content_encoded = _end_content
  1500.     _end_fullitem = _end_content
  1501.     _end_prodlink = _end_content
  1502.  
  1503.     def _start_itunes_image(self, attrsD):
  1504.         self.push('itunes_image', 0)
  1505.         self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
  1506.     _start_itunes_link = _start_itunes_image
  1507.         
  1508.     def _end_itunes_block(self):
  1509.         value = self.pop('itunes_block', 0)
  1510.         self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
  1511.  
  1512.     def _end_itunes_explicit(self):
  1513.         value = self.pop('itunes_explicit', 0)
  1514.         self._getContext()['itunes_explicit'] = (value == 'yes') and 1 or 0
  1515.  
  1516. if _XML_AVAILABLE:
  1517.     class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
  1518.         def __init__(self, baseuri, baselang, encoding):
  1519.             if _debug: sys.stderr.write('trying StrictFeedParser\n')
  1520.             xml.sax.handler.ContentHandler.__init__(self)
  1521.             _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1522.             self.bozo = 0
  1523.             self.exc = None
  1524.         
  1525.         def startPrefixMapping(self, prefix, uri):
  1526.             self.trackNamespace(prefix, uri)
  1527.         
  1528.         def startElementNS(self, name, qname, attrs):
  1529.             namespace, localname = name
  1530.             lowernamespace = str(namespace or '').lower()
  1531.             if lowernamespace.find('backend.userland.com/rss') <> -1:
  1532.                 # match any backend.userland.com namespace
  1533.                 namespace = 'http://backend.userland.com/rss'
  1534.                 lowernamespace = namespace
  1535.             if qname and qname.find(':') > 0:
  1536.                 givenprefix = qname.split(':')[0]
  1537.             else:
  1538.                 givenprefix = None
  1539.             prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1540.             if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and not self.namespacesInUse.has_key(givenprefix):
  1541.                     raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
  1542.             if prefix:
  1543.                 localname = prefix + ':' + localname
  1544.             localname = str(localname).lower()
  1545.             if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % (qname, namespace, givenprefix, prefix, attrs.items(), localname))
  1546.  
  1547.             # qname implementation is horribly broken in Python 2.1 (it
  1548.             # doesn't report any), and slightly broken in Python 2.2 (it
  1549.             # doesn't report the xml: namespace). So we match up namespaces
  1550.             # with a known list first, and then possibly override them with
  1551.             # the qnames the SAX parser gives us (if indeed it gives us any
  1552.             # at all).  Thanks to MatejC for helping me test this and
  1553.             # tirelessly telling me that it didn't work yet.
  1554.             attrsD = {}
  1555.             for (namespace, attrlocalname), attrvalue in attrs._attrs.items():
  1556.                 lowernamespace = (namespace or '').lower()
  1557.                 prefix = self._matchnamespaces.get(lowernamespace, '')
  1558.                 if prefix:
  1559.                     attrlocalname = prefix + ':' + attrlocalname
  1560.                 attrsD[str(attrlocalname).lower()] = attrvalue
  1561.             for qname in attrs.getQNames():
  1562.                 attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
  1563.             self.unknown_starttag(localname, attrsD.items())
  1564.  
  1565.         def characters(self, text):
  1566.             self.handle_data(text)
  1567.  
  1568.         def endElementNS(self, name, qname):
  1569.             namespace, localname = name
  1570.             lowernamespace = str(namespace or '').lower()
  1571.             if qname and qname.find(':') > 0:
  1572.                 givenprefix = qname.split(':')[0]
  1573.             else:
  1574.                 givenprefix = ''
  1575.             prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1576.             if prefix:
  1577.                 localname = prefix + ':' + localname
  1578.             localname = str(localname).lower()
  1579.             self.unknown_endtag(localname)
  1580.  
  1581.         def error(self, exc):
  1582.             self.bozo = 1
  1583.             self.exc = exc
  1584.             
  1585.         def fatalError(self, exc):
  1586.             self.error(exc)
  1587.             raise exc
  1588.  
  1589. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  1590.     elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
  1591.       'img', 'input', 'isindex', 'link', 'meta', 'param']
  1592.     
  1593.     def __init__(self, encoding):
  1594.         self.encoding = encoding
  1595.         if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding)
  1596.         sgmllib.SGMLParser.__init__(self)
  1597.         
  1598.     def reset(self):
  1599.         self.pieces = []
  1600.         sgmllib.SGMLParser.reset(self)
  1601.  
  1602.     def _shorttag_replace(self, match):
  1603.         tag = match.group(1)
  1604.         if tag in self.elements_no_end_tag:
  1605.             return '<' + tag + ' />'
  1606.         else:
  1607.             return '<' + tag + '></' + tag + '>'
  1608.         
  1609.     def feed(self, data):
  1610.         data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'<!\1', data)
  1611.         #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
  1612.         data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) 
  1613.         data = data.replace(''', "'")
  1614.         data = data.replace('"', '"')
  1615.         if self.encoding and type(data) == type(u''):
  1616.             data = data.encode(self.encoding)
  1617.         sgmllib.SGMLParser.feed(self, data)
  1618.  
  1619.     def normalize_attrs(self, attrs):
  1620.         # utility method to be called by descendants
  1621.         attrs = [(k.lower(), v) for k, v in attrs]
  1622.         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  1623.         return attrs
  1624.  
  1625.     def parse_starttag(self, i):
  1626.         retval = sgmllib.SGMLParser.parse_starttag(self, i)
  1627.         try:
  1628.             if self.get_starttag_text()[-2:] == "/>":
  1629.                 self.finish_endtag(self.lasttag)
  1630.         except:
  1631.             pass
  1632.         return retval
  1633.  
  1634.     def unknown_starttag(self, tag, attrs):
  1635.         # called for each start tag
  1636.         # attrs is a list of (attr, value) tuples
  1637.         # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  1638.         if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
  1639.         uattrs = []
  1640.         # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  1641.         for key, value in attrs:
  1642.             if type(value) != type(u''):
  1643.                 value = unicode(value, self.encoding)
  1644.             uattrs.append((unicode(key, self.encoding), value))
  1645.         strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
  1646.         if tag in self.elements_no_end_tag:
  1647.             self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
  1648.         else:
  1649.             self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
  1650.  
  1651.     def unknown_endtag(self, tag):
  1652.         # called for each end tag, e.g. for </pre>, tag will be 'pre'
  1653.         # Reconstruct the original end tag.
  1654.         if tag not in self.elements_no_end_tag:
  1655.             self.pieces.append("</%(tag)s>" % locals())
  1656.  
  1657.     def handle_charref(self, ref):
  1658.         # called for each character reference, e.g. for ' ', ref will be '160'
  1659.         # Reconstruct the original character reference.
  1660.         self.pieces.append('&#%(ref)s;' % locals())
  1661.         
  1662.     def handle_entityref(self, ref):
  1663.         # called for each entity reference, e.g. for '©', ref will be 'copy'
  1664.         # Reconstruct the original entity reference.
  1665.         self.pieces.append('&%(ref)s;' % locals())
  1666.  
  1667.     def handle_data(self, text):
  1668.         # called for each block of plain text, i.e. outside of any tag and
  1669.         # not containing any character or entity references
  1670.         # Store the original text verbatim.
  1671.         if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text)
  1672.         self.pieces.append(text)
  1673.         
  1674.     def handle_comment(self, text):
  1675.         # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  1676.         # Reconstruct the original comment.
  1677.         self.pieces.append('<!--%(text)s-->' % locals())
  1678.         
  1679.     def handle_pi(self, text):
  1680.         # called for each processing instruction, e.g. <?instruction>
  1681.         # Reconstruct original processing instruction.
  1682.         self.pieces.append('<?%(text)s>' % locals())
  1683.  
  1684.     def handle_decl(self, text):
  1685.         # called for the DOCTYPE, if present, e.g.
  1686.         # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  1687.         #     "http://www.w3.org/TR/html4/loose.dtd">
  1688.         # Reconstruct original DOCTYPE
  1689.         self.pieces.append('<!%(text)s>' % locals())
  1690.         
  1691.     _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  1692.     def _scan_name(self, i, declstartpos):
  1693.         rawdata = self.rawdata
  1694.         n = len(rawdata)
  1695.         if i == n:
  1696.             return None, -1
  1697.         m = self._new_declname_match(rawdata, i)
  1698.         if m:
  1699.             s = m.group()
  1700.             name = s.strip()
  1701.             if (i + len(s)) == n:
  1702.                 return None, -1  # end of buffer
  1703.             return name.lower(), m.end()
  1704.         else:
  1705.             self.handle_data(rawdata)
  1706. #            self.updatepos(declstartpos, i)
  1707.             return None, -1
  1708.  
  1709.     def output(self):
  1710.         '''Return processed HTML as a single string'''
  1711.         return ''.join([str(p) for p in self.pieces])
  1712.  
  1713. class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
  1714.     def __init__(self, baseuri, baselang, encoding):
  1715.         sgmllib.SGMLParser.__init__(self)
  1716.         _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1717.  
  1718.     def decodeEntities(self, element, data):
  1719.         data = data.replace('<', '<')
  1720.         data = data.replace('<', '<')
  1721.         data = data.replace('>', '>')
  1722.         data = data.replace('>', '>')
  1723.         data = data.replace('&', '&')
  1724.         data = data.replace('&', '&')
  1725.         data = data.replace('"', '"')
  1726.         data = data.replace('"', '"')
  1727.         data = data.replace(''', ''')
  1728.         data = data.replace(''', ''')
  1729.         if self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  1730.             data = data.replace('<', '<')
  1731.             data = data.replace('>', '>')
  1732.             data = data.replace('&', '&')
  1733.             data = data.replace('"', '"')
  1734.             data = data.replace(''', "'")
  1735.         return data
  1736.         
  1737. class _RelativeURIResolver(_BaseHTMLProcessor):
  1738.     relative_uris = [('a', 'href'),
  1739.                      ('applet', 'codebase'),
  1740.                      ('area', 'href'),
  1741.                      ('blockquote', 'cite'),
  1742.                      ('body', 'background'),
  1743.                      ('del', 'cite'),
  1744.                      ('form', 'action'),
  1745.                      ('frame', 'longdesc'),
  1746.                      ('frame', 'src'),
  1747.                      ('iframe', 'longdesc'),
  1748.                      ('iframe', 'src'),
  1749.                      ('head', 'profile'),
  1750.                      ('img', 'longdesc'),
  1751.                      ('img', 'src'),
  1752.                      ('img', 'usemap'),
  1753.                      ('input', 'src'),
  1754.                      ('input', 'usemap'),
  1755.                      ('ins', 'cite'),
  1756.                      ('link', 'href'),
  1757.                      ('object', 'classid'),
  1758.                      ('object', 'codebase'),
  1759.                      ('object', 'data'),
  1760.                      ('object', 'usemap'),
  1761.                      ('q', 'cite'),
  1762.                      ('script', 'src')]
  1763.  
  1764.     def __init__(self, baseuri, encoding):
  1765.         _BaseHTMLProcessor.__init__(self, encoding)
  1766.         self.baseuri = baseuri
  1767.  
  1768.     def resolveURI(self, uri):
  1769.         return _urljoin(self.baseuri, uri)
  1770.     
  1771.     def unknown_starttag(self, tag, attrs):
  1772.         attrs = self.normalize_attrs(attrs)
  1773.         attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
  1774.         _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1775.         
  1776. def _resolveRelativeURIs(htmlSource, baseURI, encoding):
  1777.     if _debug: sys.stderr.write('entering _resolveRelativeURIs\n')
  1778.     p = _RelativeURIResolver(baseURI, encoding)
  1779.     p.feed(htmlSource)
  1780.     return p.output()
  1781.  
  1782. class _HTMLSanitizer(_BaseHTMLProcessor):
  1783.     acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
  1784.       'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
  1785.       'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',
  1786.       'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input',
  1787.       'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup',
  1788.       'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',
  1789.       'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',
  1790.       'thead', 'tr', 'tt', 'u', 'ul', 'var']
  1791.  
  1792.     acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  1793.       'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
  1794.       'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
  1795.       'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled',
  1796.       'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace',
  1797.       'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
  1798.       'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
  1799.       'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
  1800.       'span', 'src', 'start', 'summary', 'tabindex', 'title', 'type',
  1801.       'usemap', 'valign', 'value', 'vspace', 'width']
  1802.  
  1803.     unacceptable_elements_with_end_tag = ['script', 'applet']
  1804.  
  1805.     def reset(self):
  1806.         _BaseHTMLProcessor.reset(self)
  1807.         self.unacceptablestack = 0
  1808.         
  1809.     def unknown_starttag(self, tag, attrs):
  1810.         if not tag in self.acceptable_elements:
  1811.             if tag in self.unacceptable_elements_with_end_tag:
  1812.                 self.unacceptablestack += 1
  1813.             return
  1814.         attrs = self.normalize_attrs(attrs)
  1815.         attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes]
  1816.         _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1817.         
  1818.     def unknown_endtag(self, tag):
  1819.         if not tag in self.acceptable_elements:
  1820.             if tag in self.unacceptable_elements_with_end_tag:
  1821.                 self.unacceptablestack -= 1
  1822.             return
  1823.         _BaseHTMLProcessor.unknown_endtag(self, tag)
  1824.  
  1825.     def handle_pi(self, text):
  1826.         pass
  1827.  
  1828.     def handle_decl(self, text):
  1829.         pass
  1830.  
  1831.     def handle_data(self, text):
  1832.         if not self.unacceptablestack:
  1833.             _BaseHTMLProcessor.handle_data(self, text)
  1834.  
  1835. def sanitizeHTML(htmlSource, encoding):
  1836.     p = _HTMLSanitizer(encoding)
  1837.     p.feed(htmlSource)
  1838.     data = p.output()
  1839.     if TIDY_MARKUP:
  1840.         # loop through list of preferred Tidy interfaces looking for one that's installed,
  1841.         # then set up a common _tidy function to wrap the interface-specific API.
  1842.         _tidy = None
  1843.         for tidy_interface in PREFERRED_TIDY_INTERFACES:
  1844.             try:
  1845.                 if tidy_interface == "uTidy":
  1846.                     from tidy import parseString as _utidy
  1847.                     def _tidy(data, **kwargs):
  1848.                         return str(_utidy(data, **kwargs))
  1849.                     break
  1850.                 elif tidy_interface == "mxTidy":
  1851.                     from mx.Tidy import Tidy as _mxtidy
  1852.                     def _tidy(data, **kwargs):
  1853.                         nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs)
  1854.                         return data
  1855.                     break
  1856.             except:
  1857.                 pass
  1858.         if _tidy:
  1859.             utf8 = type(data) == type(u'')
  1860.             if utf8:
  1861.                 data = data.encode('utf-8')
  1862.             data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8")
  1863.             if utf8:
  1864.                 data = unicode(data, 'utf-8')
  1865.             if data.count('<body'):
  1866.                 data = data.split('<body', 1)[1]
  1867.                 if data.count('>'):
  1868.                     data = data.split('>', 1)[1]
  1869.             if data.count('</body'):
  1870.                 data = data.split('</body', 1)[0]
  1871.     data = data.strip().replace('\r\n', '\n')
  1872.     return data
  1873.  
  1874. class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
  1875.     def http_error_default(self, req, fp, code, msg, headers):
  1876.         if ((code / 100) == 3) and (code != 304):
  1877.             return self.http_error_302(req, fp, code, msg, headers)
  1878.         infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1879.         infourl.status = code
  1880.         return infourl
  1881.  
  1882.     def http_error_302(self, req, fp, code, msg, headers):
  1883.         if headers.dict.has_key('location'):
  1884.             infourl = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
  1885.         else:
  1886.             infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1887.         if not hasattr(infourl, 'status'):
  1888.             infourl.status = code
  1889.         return infourl
  1890.  
  1891.     def http_error_301(self, req, fp, code, msg, headers):
  1892.         if headers.dict.has_key('location'):
  1893.             infourl = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
  1894.         else:
  1895.             infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1896.         if not hasattr(infourl, 'status'):
  1897.             infourl.status = code
  1898.         return infourl
  1899.  
  1900.     http_error_300 = http_error_302
  1901.     http_error_303 = http_error_302
  1902.     http_error_307 = http_error_302
  1903.         
  1904.     def http_error_401(self, req, fp, code, msg, headers):
  1905.         # Check if
  1906.         # - server requires digest auth, AND
  1907.         # - we tried (unsuccessfully) with basic auth, AND
  1908.         # - we're using Python 2.3.3 or later (digest auth is irreparably broken in earlier versions)
  1909.         # If all conditions hold, parse authentication information
  1910.         # out of the Authorization header we sent the first time
  1911.         # (for the username and password) and the WWW-Authenticate
  1912.         # header the server sent back (for the realm) and retry
  1913.         # the request with the appropriate digest auth headers instead.
  1914.         # This evil genius hack has been brought to you by Aaron Swartz.
  1915.         host = urlparse.urlparse(req.get_full_url())[1]
  1916.         try:
  1917.             assert sys.version.split()[0] >= '2.3.3'
  1918.             assert base64 != None
  1919.             user, passw = base64.decodestring(req.headers['Authorization'].split(' ')[1]).split(':')
  1920.             realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
  1921.             self.add_password(realm, host, user, passw)
  1922.             retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  1923.             self.reset_retry_count()
  1924.             return retry
  1925.         except:
  1926.             return self.http_error_default(req, fp, code, msg, headers)
  1927.  
  1928. def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers):
  1929.     """URL, filename, or string --> stream
  1930.  
  1931.     This function lets you define parsers that take any input source
  1932.     (URL, pathname to local or network file, or actual data as a string)
  1933.     and deal with it in a uniform manner.  Returned object is guaranteed
  1934.     to have all the basic stdio read methods (read, readline, readlines).
  1935.     Just .close() the object when you're done with it.
  1936.  
  1937.     If the etag argument is supplied, it will be used as the value of an
  1938.     If-None-Match request header.
  1939.  
  1940.     If the modified argument is supplied, it must be a tuple of 9 integers
  1941.     as returned by gmtime() in the standard Python time module. This MUST
  1942.     be in GMT (Greenwich Mean Time). The formatted date/time will be used
  1943.     as the value of an If-Modified-Since request header.
  1944.  
  1945.     If the agent argument is supplied, it will be used as the value of a
  1946.     User-Agent request header.
  1947.  
  1948.     If the referrer argument is supplied, it will be used as the value of a
  1949.     Referer[sic] request header.
  1950.  
  1951.     If handlers is supplied, it is a list of handlers used to build a
  1952.     urllib2 opener.
  1953.     """
  1954.  
  1955.     if hasattr(url_file_stream_or_string, 'read'):
  1956.         return url_file_stream_or_string
  1957.  
  1958.     if url_file_stream_or_string == '-':
  1959.         return sys.stdin
  1960.  
  1961.     if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
  1962.         if not agent:
  1963.             agent = USER_AGENT
  1964.         # test for inline user:password for basic auth
  1965.         auth = None
  1966.         if base64:
  1967.             urltype, rest = urllib.splittype(url_file_stream_or_string)
  1968.             realhost, rest = urllib.splithost(rest)
  1969.             if realhost:
  1970.                 user_passwd, realhost = urllib.splituser(realhost)
  1971.                 if user_passwd:
  1972.                     url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
  1973.                     auth = base64.encodestring(user_passwd).strip()
  1974.         # try to open with urllib2 (to use optional headers)
  1975.         request = urllib2.Request(url_file_stream_or_string)
  1976.         request.add_header('User-Agent', agent)
  1977.         if etag:
  1978.             request.add_header('If-None-Match', etag)
  1979.         if modified:
  1980.             # format into an RFC 1123-compliant timestamp. We can't use
  1981.             # time.strftime() since the %a and %b directives can be affected
  1982.             # by the current locale, but RFC 2616 states that dates must be
  1983.             # in English.
  1984.             short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  1985.             months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  1986.             request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5]))
  1987.         if referrer:
  1988.             request.add_header('Referer', referrer)
  1989.         if gzip and zlib:
  1990.             request.add_header('Accept-encoding', 'gzip, deflate')
  1991.         elif gzip:
  1992.             request.add_header('Accept-encoding', 'gzip')
  1993.         elif zlib:
  1994.             request.add_header('Accept-encoding', 'deflate')
  1995.         else:
  1996.             request.add_header('Accept-encoding', '')
  1997.         if auth:
  1998.             request.add_header('Authorization', 'Basic %s' % auth)
  1999.         if ACCEPT_HEADER:
  2000.             request.add_header('Accept', ACCEPT_HEADER)
  2001.         request.add_header('A-IM', 'feed') # RFC 3229 support
  2002.         opener = apply(urllib2.build_opener, tuple([_FeedURLHandler()] + handlers))
  2003.         opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
  2004.         try:
  2005.             return opener.open(request)
  2006.         finally:
  2007.             opener.close() # JohnD
  2008.     
  2009.     # try to open with native open function (if url_file_stream_or_string is a filename)
  2010.     try:
  2011.         return open(url_file_stream_or_string)
  2012.     except:
  2013.         pass
  2014.  
  2015.     # treat url_file_stream_or_string as string
  2016.     return _StringIO(str(url_file_stream_or_string))
  2017.  
  2018. _date_handlers = []
  2019. def registerDateHandler(func):
  2020.     '''Register a date handler function (takes string, returns 9-tuple date in GMT)'''
  2021.     _date_handlers.insert(0, func)
  2022.     
  2023. # ISO-8601 date parsing routines written by Fazal Majid.
  2024. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
  2025. # parser is beyond the scope of feedparser and would be a worthwhile addition
  2026. # to the Python library.
  2027. # A single regular expression cannot parse ISO 8601 date formats into groups
  2028. # as the standard is highly irregular (for instance is 030104 2003-01-04 or
  2029. # 0301-04-01), so we use templates instead.
  2030. # Please note the order in templates is significant because we need a
  2031. # greedy match.
  2032. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
  2033.                 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', 
  2034.                 '-YY-?MM', '-OOO', '-YY',
  2035.                 '--MM-?DD', '--MM',
  2036.                 '---DD',
  2037.                 'CC', '']
  2038. _iso8601_re = [
  2039.     tmpl.replace(
  2040.     'YYYY', r'(?P<year>\d{4})').replace(
  2041.     'YY', r'(?P<year>\d\d)').replace(
  2042.     'MM', r'(?P<month>[01]\d)').replace(
  2043.     'DD', r'(?P<day>[0123]\d)').replace(
  2044.     'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
  2045.     'CC', r'(?P<century>\d\d$)')
  2046.     + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
  2047.     + r'(:(?P<second>\d{2}))?'
  2048.     + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
  2049.     for tmpl in _iso8601_tmpl]
  2050. del tmpl
  2051. _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
  2052. del regex
  2053. def _parse_date_iso8601(dateString):
  2054.     '''Parse a variety of ISO-8601-compatible formats like 20040105'''
  2055.     m = None
  2056.     for _iso8601_match in _iso8601_matches:
  2057.         m = _iso8601_match(dateString)
  2058.         if m: break
  2059.     if not m: return
  2060.     if m.span() == (0, 0): return
  2061.     params = m.groupdict()
  2062.     ordinal = params.get('ordinal', 0)
  2063.     if ordinal:
  2064.         ordinal = int(ordinal)
  2065.     else:
  2066.         ordinal = 0
  2067.     year = params.get('year', '--')
  2068.     if not year or year == '--':
  2069.         year = time.gmtime()[0]
  2070.     elif len(year) == 2:
  2071.         # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
  2072.         year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2073.     else:
  2074.         year = int(year)
  2075.     month = params.get('month', '-')
  2076.     if not month or month == '-':
  2077.         # ordinals are NOT normalized by mktime, we simulate them
  2078.         # by setting month=1, day=ordinal
  2079.         if ordinal:
  2080.             month = 1
  2081.         else:
  2082.             month = time.gmtime()[1]
  2083.     month = int(month)
  2084.     day = params.get('day', 0)
  2085.     if not day:
  2086.         # see above
  2087.         if ordinal:
  2088.             day = ordinal
  2089.         elif params.get('century', 0) or \
  2090.                  params.get('year', 0) or params.get('month', 0):
  2091.             day = 1
  2092.         else:
  2093.             day = time.gmtime()[2]
  2094.     else:
  2095.         day = int(day)
  2096.     # special case of the century - is the first year of the 21st century
  2097.     # 2000 or 2001 ? The debate goes on...
  2098.     if 'century' in params.keys():
  2099.         year = (int(params['century']) - 1) * 100 + 1
  2100.     # in ISO 8601 most fields are optional
  2101.     for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
  2102.         if not params.get(field, None):
  2103.             params[field] = 0
  2104.     hour = int(params.get('hour', 0))
  2105.     minute = int(params.get('minute', 0))
  2106.     second = int(params.get('second', 0))
  2107.     # weekday is normalized by mktime(), we can ignore it
  2108.     weekday = 0
  2109.     # daylight savings is complex, but not needed for feedparser's purposes
  2110.     # as time zones, if specified, include mention of whether it is active
  2111.     # (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and
  2112.     # and most implementations have DST bugs
  2113.     daylight_savings_flag = 0
  2114.     tm = [year, month, day, hour, minute, second, weekday,
  2115.           ordinal, daylight_savings_flag]
  2116.     # ISO 8601 time zone adjustments
  2117.     tz = params.get('tz')
  2118.     if tz and tz != 'Z':
  2119.         if tz[0] == '-':
  2120.             tm[3] += int(params.get('tzhour', 0))
  2121.             tm[4] += int(params.get('tzmin', 0))
  2122.         elif tz[0] == '+':
  2123.             tm[3] -= int(params.get('tzhour', 0))
  2124.             tm[4] -= int(params.get('tzmin', 0))
  2125.         else:
  2126.             return None
  2127.     # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
  2128.     # which is guaranteed to normalize d/m/y/h/m/s.
  2129.     # Many implementations have bugs, but we'll pretend they don't.
  2130.     return time.localtime(time.mktime(tm))
  2131. registerDateHandler(_parse_date_iso8601)
  2132.     
  2133. # 8-bit date handling routines written by ytrewq1.
  2134. _korean_year  = u'\ub144' # b3e2 in euc-kr
  2135. _korean_month = u'\uc6d4' # bff9 in euc-kr
  2136. _korean_day   = u'\uc77c' # c0cf in euc-kr
  2137. _korean_am    = u'\uc624\uc804' # bfc0 c0fc in euc-kr
  2138. _korean_pm    = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
  2139.  
  2140. _korean_onblog_date_re = \
  2141.     re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
  2142.                (_korean_year, _korean_month, _korean_day))
  2143. _korean_nate_date_re = \
  2144.     re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
  2145.                (_korean_am, _korean_pm))
  2146. def _parse_date_onblog(dateString):
  2147.     '''Parse a string according to the OnBlog 8-bit date format'''
  2148.     m = _korean_onblog_date_re.match(dateString)
  2149.     if not m: return
  2150.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2151.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2152.                  'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2153.                  'zonediff': '+09:00'}
  2154.     if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate)
  2155.     return _parse_date_w3dtf(w3dtfdate)
  2156. registerDateHandler(_parse_date_onblog)
  2157.  
  2158. def _parse_date_nate(dateString):
  2159.     '''Parse a string according to the Nate 8-bit date format'''
  2160.     m = _korean_nate_date_re.match(dateString)
  2161.     if not m: return
  2162.     hour = int(m.group(5))
  2163.     ampm = m.group(4)
  2164.     if (ampm == _korean_pm):
  2165.         hour += 12
  2166.     hour = str(hour)
  2167.     if len(hour) == 1:
  2168.         hour = '0' + hour
  2169.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2170.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2171.                  'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
  2172.                  'zonediff': '+09:00'}
  2173.     if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate)
  2174.     return _parse_date_w3dtf(w3dtfdate)
  2175. registerDateHandler(_parse_date_nate)
  2176.  
  2177. _mssql_date_re = \
  2178.     re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?')
  2179. def _parse_date_mssql(dateString):
  2180.     '''Parse a string according to the MS SQL date format'''
  2181.     m = _mssql_date_re.match(dateString)
  2182.     if not m: return
  2183.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2184.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2185.                  'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2186.                  'zonediff': '+09:00'}
  2187.     if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate)
  2188.     return _parse_date_w3dtf(w3dtfdate)
  2189. registerDateHandler(_parse_date_mssql)
  2190.  
  2191. # Unicode strings for Greek date strings
  2192. _greek_months = \
  2193.   { \
  2194.    u'\u0399\u03b1\u03bd': u'Jan',       # c9e1ed in iso-8859-7
  2195.    u'\u03a6\u03b5\u03b2': u'Feb',       # d6e5e2 in iso-8859-7
  2196.    u'\u039c\u03ac\u03ce': u'Mar',       # ccdcfe in iso-8859-7
  2197.    u'\u039c\u03b1\u03ce': u'Mar',       # cce1fe in iso-8859-7
  2198.    u'\u0391\u03c0\u03c1': u'Apr',       # c1f0f1 in iso-8859-7
  2199.    u'\u039c\u03ac\u03b9': u'May',       # ccdce9 in iso-8859-7
  2200.    u'\u039c\u03b1\u03ca': u'May',       # cce1fa in iso-8859-7
  2201.    u'\u039c\u03b1\u03b9': u'May',       # cce1e9 in iso-8859-7
  2202.    u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
  2203.    u'\u0399\u03bf\u03bd': u'Jun',       # c9efed in iso-8859-7
  2204.    u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
  2205.    u'\u0399\u03bf\u03bb': u'Jul',       # c9f9eb in iso-8859-7
  2206.    u'\u0391\u03cd\u03b3': u'Aug',       # c1fde3 in iso-8859-7
  2207.    u'\u0391\u03c5\u03b3': u'Aug',       # c1f5e3 in iso-8859-7
  2208.    u'\u03a3\u03b5\u03c0': u'Sep',       # d3e5f0 in iso-8859-7
  2209.    u'\u039f\u03ba\u03c4': u'Oct',       # cfeaf4 in iso-8859-7
  2210.    u'\u039d\u03bf\u03ad': u'Nov',       # cdefdd in iso-8859-7
  2211.    u'\u039d\u03bf\u03b5': u'Nov',       # cdefe5 in iso-8859-7
  2212.    u'\u0394\u03b5\u03ba': u'Dec',       # c4e5ea in iso-8859-7
  2213.   }
  2214.  
  2215. _greek_wdays = \
  2216.   { \
  2217.    u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
  2218.    u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
  2219.    u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
  2220.    u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
  2221.    u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
  2222.    u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
  2223.    u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7   
  2224.   }
  2225.  
  2226. _greek_date_format_re = \
  2227.     re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
  2228.  
  2229. def _parse_date_greek(dateString):
  2230.     '''Parse a string according to a Greek 8-bit date format.'''
  2231.     m = _greek_date_format_re.match(dateString)
  2232.     if not m: return
  2233.     try:
  2234.         wday = _greek_wdays[m.group(1)]
  2235.         month = _greek_months[m.group(3)]
  2236.     except:
  2237.         return
  2238.     rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
  2239.                  {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
  2240.                   'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
  2241.                   'zonediff': m.group(8)}
  2242.     if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date)
  2243.     return _parse_date_rfc822(rfc822date)
  2244. registerDateHandler(_parse_date_greek)
  2245.  
  2246. # Unicode strings for Hungarian date strings
  2247. _hungarian_months = \
  2248.   { \
  2249.     u'janu\u00e1r':   u'01',  # e1 in iso-8859-2
  2250.     u'febru\u00e1ri': u'02',  # e1 in iso-8859-2
  2251.     u'm\u00e1rcius':  u'03',  # e1 in iso-8859-2
  2252.     u'\u00e1prilis':  u'04',  # e1 in iso-8859-2
  2253.     u'm\u00e1ujus':   u'05',  # e1 in iso-8859-2
  2254.     u'j\u00fanius':   u'06',  # fa in iso-8859-2
  2255.     u'j\u00falius':   u'07',  # fa in iso-8859-2
  2256.     u'augusztus':     u'08',
  2257.     u'szeptember':    u'09',
  2258.     u'okt\u00f3ber':  u'10',  # f3 in iso-8859-2
  2259.     u'november':      u'11',
  2260.     u'december':      u'12',
  2261.   }
  2262.  
  2263. _hungarian_date_format_re = \
  2264.   re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
  2265.  
  2266. def _parse_date_hungarian(dateString):
  2267.     '''Parse a string according to a Hungarian 8-bit date format.'''
  2268.     m = _hungarian_date_format_re.match(dateString)
  2269.     if not m: return
  2270.     try:
  2271.         month = _hungarian_months[m.group(2)]
  2272.         day = m.group(3)
  2273.         if len(day) == 1:
  2274.             day = '0' + day
  2275.         hour = m.group(4)
  2276.         if len(hour) == 1:
  2277.             hour = '0' + hour
  2278.     except:
  2279.         return
  2280.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
  2281.                 {'year': m.group(1), 'month': month, 'day': day,\
  2282.                  'hour': hour, 'minute': m.group(5),\
  2283.                  'zonediff': m.group(6)}
  2284.     if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate)
  2285.     return _parse_date_w3dtf(w3dtfdate)
  2286. registerDateHandler(_parse_date_hungarian)
  2287.  
  2288. # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
  2289. # Drake and licensed under the Python license.  Removed all range checking
  2290. # for month, day, hour, minute, and second, since mktime will normalize
  2291. # these later
  2292. def _parse_date_w3dtf(dateString):
  2293.     def __extract_date(m):
  2294.         year = int(m.group('year'))
  2295.         if year < 100:
  2296.             year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2297.         if year < 1000:
  2298.             return 0, 0, 0
  2299.         julian = m.group('julian')
  2300.         if julian:
  2301.             julian = int(julian)
  2302.             month = julian / 30 + 1
  2303.             day = julian % 30 + 1
  2304.             jday = None
  2305.             while jday != julian:
  2306.                 t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
  2307.                 jday = time.gmtime(t)[-2]
  2308.                 diff = abs(jday - julian)
  2309.                 if jday > julian:
  2310.                     if diff < day:
  2311.                         day = day - diff
  2312.                     else:
  2313.                         month = month - 1
  2314.                         day = 31
  2315.                 elif jday < julian:
  2316.                     if day + diff < 28:
  2317.                        day = day + diff
  2318.                     else:
  2319.                         month = month + 1
  2320.             return year, month, day
  2321.         month = m.group('month')
  2322.         day = 1
  2323.         if month is None:
  2324.             month = 1
  2325.         else:
  2326.             month = int(month)
  2327.             day = m.group('day')
  2328.             if day:
  2329.                 day = int(day)
  2330.             else:
  2331.                 day = 1
  2332.         return year, month, day
  2333.  
  2334.     def __extract_time(m):
  2335.         if not m:
  2336.             return 0, 0, 0
  2337.         hours = m.group('hours')
  2338.         if not hours:
  2339.             return 0, 0, 0
  2340.         hours = int(hours)
  2341.         minutes = int(m.group('minutes'))
  2342.         seconds = m.group('seconds')
  2343.         if seconds:
  2344.             seconds = int(seconds)
  2345.         else:
  2346.             seconds = 0
  2347.         return hours, minutes, seconds
  2348.  
  2349.     def __extract_tzd(m):
  2350.         '''Return the Time Zone Designator as an offset in seconds from UTC.'''
  2351.         if not m:
  2352.             return 0
  2353.         tzd = m.group('tzd')
  2354.         if not tzd:
  2355.             return 0
  2356.         if tzd == 'Z':
  2357.             return 0
  2358.         hours = int(m.group('tzdhours'))
  2359.         minutes = m.group('tzdminutes')
  2360.         if minutes:
  2361.             minutes = int(minutes)
  2362.         else:
  2363.             minutes = 0
  2364.         offset = (hours*60 + minutes) * 60
  2365.         if tzd[0] == '+':
  2366.             return -offset
  2367.         return offset
  2368.  
  2369.     __date_re = ('(?P<year>\d\d\d\d)'
  2370.                  '(?:(?P<dsep>-|)'
  2371.                  '(?:(?P<julian>\d\d\d)'
  2372.                  '|(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?))?')
  2373.     __tzd_re = '(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)'
  2374.     __tzd_rx = re.compile(__tzd_re)
  2375.     __time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)'
  2376.                  '(?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?'
  2377.                  + __tzd_re)
  2378.     __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re)
  2379.     __datetime_rx = re.compile(__datetime_re)
  2380.     m = __datetime_rx.match(dateString)
  2381.     if (m is None) or (m.group() != dateString): return
  2382.     gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
  2383.     if gmt[0] == 0: return
  2384.     return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone)
  2385. registerDateHandler(_parse_date_w3dtf)
  2386.  
  2387. def _parse_date_rfc822(dateString):
  2388.     '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
  2389.     data = dateString.split()
  2390.     if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
  2391.         del data[0]
  2392.     if len(data) == 4:
  2393.         s = data[3]
  2394.         i = s.find('+')
  2395.         if i > 0:
  2396.             data[3:] = [s[:i], s[i+1:]]
  2397.         else:
  2398.             data.append('')
  2399.         dateString = " ".join(data)
  2400.     if len(data) < 5:
  2401.         dateString += ' 00:00:00 GMT'
  2402.     tm = rfc822.parsedate_tz(dateString)
  2403.     if tm:
  2404.         return time.gmtime(rfc822.mktime_tz(tm))
  2405. # rfc822.py defines several time zones, but we define some extra ones.
  2406. # 'ET' is equivalent to 'EST', etc.
  2407. _additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800}
  2408. rfc822._timezones.update(_additional_timezones)
  2409. registerDateHandler(_parse_date_rfc822)    
  2410.  
  2411. def _parse_date(dateString):
  2412.     '''Parses a variety of date formats into a 9-tuple in GMT'''
  2413.     for handler in _date_handlers:
  2414.         try:
  2415.             date9tuple = handler(dateString)
  2416.             if not date9tuple: continue
  2417.             if len(date9tuple) != 9:
  2418.                 if _debug: sys.stderr.write('date handler function must return 9-tuple\n')
  2419.                 raise ValueError
  2420.             map(int, date9tuple)
  2421.             return date9tuple
  2422.         except Exception, e:
  2423.             if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e)))
  2424.             pass
  2425.     return None
  2426.  
  2427. def _getCharacterEncoding(http_headers, xml_data):
  2428.     '''Get the character encoding of the XML document
  2429.  
  2430.     http_headers is a dictionary
  2431.     xml_data is a raw string (not Unicode)
  2432.     
  2433.     This is so much trickier than it sounds, it's not even funny.
  2434.     According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
  2435.     is application/xml, application/*+xml,
  2436.     application/xml-external-parsed-entity, or application/xml-dtd,
  2437.     the encoding given in the charset parameter of the HTTP Content-Type
  2438.     takes precedence over the encoding given in the XML prefix within the
  2439.     document, and defaults to 'utf-8' if neither are specified.  But, if
  2440.     the HTTP Content-Type is text/xml, text/*+xml, or
  2441.     text/xml-external-parsed-entity, the encoding given in the XML prefix
  2442.     within the document is ALWAYS IGNORED and only the encoding given in
  2443.     the charset parameter of the HTTP Content-Type header should be
  2444.     respected, and it defaults to 'us-ascii' if not specified.
  2445.  
  2446.     Furthermore, discussion on the atom-syntax mailing list with the
  2447.     author of RFC 3023 leads me to the conclusion that any document
  2448.     served with a Content-Type of text/* and no charset parameter
  2449.     must be treated as us-ascii.  (We now do this.)  And also that it
  2450.     must always be flagged as non-well-formed.  (We now do this too.)
  2451.     
  2452.     If Content-Type is unspecified (input was local file or non-HTTP source)
  2453.     or unrecognized (server just got it totally wrong), then go by the
  2454.     encoding given in the XML prefix of the document and default to
  2455.     'iso-8859-1' as per the HTTP specification (RFC 2616).
  2456.     
  2457.     Then, assuming we didn't find a character encoding in the HTTP headers
  2458.     (and the HTTP Content-type allowed us to look in the body), we need
  2459.     to sniff the first few bytes of the XML data and try to determine
  2460.     whether the encoding is ASCII-compatible.  Section F of the XML
  2461.     specification shows the way here:
  2462.     http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2463.  
  2464.     If the sniffed encoding is not ASCII-compatible, we need to make it
  2465.     ASCII compatible so that we can sniff further into the XML declaration
  2466.     to find the encoding attribute, which will tell us the true encoding.
  2467.  
  2468.     Of course, none of this guarantees that we will be able to parse the
  2469.     feed in the declared character encoding (assuming it was declared
  2470.     correctly, which many are not).  CJKCodecs and iconv_codec help a lot;
  2471.     you should definitely install them if you can.
  2472.     http://cjkpython.i18n.org/
  2473.     '''
  2474.  
  2475.     def _parseHTTPContentType(content_type):
  2476.         '''takes HTTP Content-Type header and returns (content type, charset)
  2477.  
  2478.         If no charset is specified, returns (content type, '')
  2479.         If no content type is specified, returns ('', '')
  2480.         Both return parameters are guaranteed to be lowercase strings
  2481.         '''
  2482.         content_type = content_type or ''
  2483.         content_type, params = cgi.parse_header(content_type)
  2484.         return content_type, params.get('charset', '').replace("'", '')
  2485.  
  2486.     sniffed_xml_encoding = ''
  2487.     xml_encoding = ''
  2488.     true_encoding = ''
  2489.     http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type'))
  2490.     # Must sniff for non-ASCII-compatible character encodings before
  2491.     # searching for XML declaration.  This heuristic is defined in
  2492.     # section F of the XML specification:
  2493.     # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2494.     try:
  2495.         if xml_data[:4] == '\x4c\x6f\xa7\x94':
  2496.             # EBCDIC
  2497.             xml_data = _ebcdic_to_ascii(xml_data)
  2498.         elif xml_data[:4] == '\x00\x3c\x00\x3f':
  2499.             # UTF-16BE
  2500.             sniffed_xml_encoding = 'utf-16be'
  2501.             xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  2502.         elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00'):
  2503.             # UTF-16BE with BOM
  2504.             sniffed_xml_encoding = 'utf-16be'
  2505.             xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  2506.         elif xml_data[:4] == '\x3c\x00\x3f\x00':
  2507.             # UTF-16LE
  2508.             sniffed_xml_encoding = 'utf-16le'
  2509.             xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  2510.         elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00'):
  2511.             # UTF-16LE with BOM
  2512.             sniffed_xml_encoding = 'utf-16le'
  2513.             xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  2514.         elif xml_data[:4] == '\x00\x00\x00\x3c':
  2515.             # UTF-32BE
  2516.             sniffed_xml_encoding = 'utf-32be'
  2517.             xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  2518.         elif xml_data[:4] == '\x3c\x00\x00\x00':
  2519.             # UTF-32LE
  2520.             sniffed_xml_encoding = 'utf-32le'
  2521.             xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  2522.         elif xml_data[:4] == '\x00\x00\xfe\xff':
  2523.             # UTF-32BE with BOM
  2524.             sniffed_xml_encoding = 'utf-32be'
  2525.             xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  2526.         elif xml_data[:4] == '\xff\xfe\x00\x00':
  2527.             # UTF-32LE with BOM
  2528.             sniffed_xml_encoding = 'utf-32le'
  2529.             xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  2530.         elif xml_data[:3] == '\xef\xbb\xbf':
  2531.             # UTF-8 with BOM
  2532.             sniffed_xml_encoding = 'utf-8'
  2533.             xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  2534.         else:
  2535.             # ASCII-compatible
  2536.             pass
  2537.         xml_encoding_match = re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
  2538.     except:
  2539.         xml_encoding_match = None
  2540.     if xml_encoding_match:
  2541.         xml_encoding = xml_encoding_match.groups()[0].lower()
  2542.         if sniffed_xml_encoding and (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')):
  2543.             xml_encoding = sniffed_xml_encoding
  2544.     acceptable_content_type = 0
  2545.     application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity')
  2546.     text_content_types = ('text/xml', 'text/xml-external-parsed-entity')
  2547.     if (http_content_type in application_content_types) or \
  2548.        (http_content_type.startswith('application/') and http_content_type.endswith('+xml')):
  2549.         acceptable_content_type = 1
  2550.         true_encoding = http_encoding or xml_encoding or 'utf-8'
  2551.     elif (http_content_type in text_content_types) or \
  2552.          (http_content_type.startswith('text/')) and http_content_type.endswith('+xml'):
  2553.         acceptable_content_type = 1
  2554.         true_encoding = http_encoding or 'us-ascii'
  2555.     elif http_content_type.startswith('text/'):
  2556.         true_encoding = http_encoding or 'us-ascii'
  2557.     elif http_headers and (not http_headers.has_key('content-type')):
  2558.         true_encoding = xml_encoding or 'iso-8859-1'
  2559.     else:
  2560.         true_encoding = xml_encoding or 'utf-8'
  2561.     return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type
  2562.     
  2563. def _toUTF8(data, encoding):
  2564.     '''Changes an XML data stream on the fly to specify a new encoding
  2565.  
  2566.     data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already
  2567.     encoding is a string recognized by encodings.aliases
  2568.     '''
  2569.     if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding)
  2570.     # strip Byte Order Mark (if present)
  2571.     if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
  2572.         if _debug:
  2573.             sys.stderr.write('stripping BOM\n')
  2574.             if encoding != 'utf-16be':
  2575.                 sys.stderr.write('trying utf-16be instead\n')
  2576.         encoding = 'utf-16be'
  2577.         data = data[2:]
  2578.     elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
  2579.         if _debug:
  2580.             sys.stderr.write('stripping BOM\n')
  2581.             if encoding != 'utf-16le':
  2582.                 sys.stderr.write('trying utf-16le instead\n')
  2583.         encoding = 'utf-16le'
  2584.         data = data[2:]
  2585.     elif data[:3] == '\xef\xbb\xbf':
  2586.         if _debug:
  2587.             sys.stderr.write('stripping BOM\n')
  2588.             if encoding != 'utf-8':
  2589.                 sys.stderr.write('trying utf-8 instead\n')
  2590.         encoding = 'utf-8'
  2591.         data = data[3:]
  2592.     elif data[:4] == '\x00\x00\xfe\xff':
  2593.         if _debug:
  2594.             sys.stderr.write('stripping BOM\n')
  2595.             if encoding != 'utf-32be':
  2596.                 sys.stderr.write('trying utf-32be instead\n')
  2597.         encoding = 'utf-32be'
  2598.         data = data[4:]
  2599.     elif data[:4] == '\xff\xfe\x00\x00':
  2600.         if _debug:
  2601.             sys.stderr.write('stripping BOM\n')
  2602.             if encoding != 'utf-32le':
  2603.                 sys.stderr.write('trying utf-32le instead\n')
  2604.         encoding = 'utf-32le'
  2605.         data = data[4:]
  2606.     newdata = unicode(data, encoding)
  2607.     if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding)
  2608.     declmatch = re.compile('^<\?xml[^>]*?>')
  2609.     newdecl = '''<?xml version='1.0' encoding='utf-8'?>'''
  2610.     if declmatch.search(newdata):
  2611.         newdata = declmatch.sub(newdecl, newdata)
  2612.     else:
  2613.         newdata = newdecl + u'\n' + newdata
  2614.     return newdata.encode('utf-8')
  2615.  
  2616. def _stripDoctype(data):
  2617.     '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
  2618.  
  2619.     rss_version may be 'rss091n' or None
  2620.     stripped_data is the same XML document, minus the DOCTYPE
  2621.     '''
  2622.     entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE)
  2623.     data = entity_pattern.sub('', data)
  2624.     doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE)
  2625.     doctype_results = doctype_pattern.findall(data)
  2626.     doctype = doctype_results and doctype_results[0] or ''
  2627.     if doctype.lower().count('netscape'):
  2628.         version = 'rss091n'
  2629.     else:
  2630.         version = None
  2631.     data = doctype_pattern.sub('', data)
  2632.     return version, data
  2633.     
  2634. def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
  2635.     '''Parse a feed from a URL, file, stream, or string'''
  2636.     result = FeedParserDict()
  2637.     result['feed'] = FeedParserDict()
  2638.     result['entries'] = []
  2639.     if _XML_AVAILABLE:
  2640.         result['bozo'] = 0
  2641.     if type(handlers) == types.InstanceType:
  2642.         handlers = [handlers]
  2643.     try:
  2644.         f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
  2645.         data = f.read()
  2646.     except Exception, e:
  2647.         result['bozo'] = 1
  2648.         result['bozo_exception'] = e
  2649.         data = ''
  2650.         f = None
  2651.  
  2652.     # if feed is gzip-compressed, decompress it
  2653.     if f and data and hasattr(f, 'headers'):
  2654.         if gzip and f.headers.get('content-encoding', '') == 'gzip':
  2655.             try:
  2656.                 data = gzip.GzipFile(fileobj=_StringIO(data)).read()
  2657.             except Exception, e:
  2658.                 # Some feeds claim to be gzipped but they're not, so
  2659.                 # we get garbage.  Ideally, we should re-request the
  2660.                 # feed without the 'Accept-encoding: gzip' header,
  2661.                 # but we don't.
  2662.                 result['bozo'] = 1
  2663.                 result['bozo_exception'] = e
  2664.                 data = ''
  2665.         elif zlib and f.headers.get('content-encoding', '') == 'deflate':
  2666.             try:
  2667.                 data = zlib.decompress(data, -zlib.MAX_WBITS)
  2668.             except Exception, e:
  2669.                 result['bozo'] = 1
  2670.                 result['bozo_exception'] = e
  2671.                 data = ''
  2672.  
  2673.     # save HTTP headers
  2674.     if hasattr(f, 'info'):
  2675.         info = f.info()
  2676.         result['etag'] = info.getheader('ETag')
  2677.         last_modified = info.getheader('Last-Modified')
  2678.         if last_modified:
  2679.             result['modified'] = _parse_date(last_modified)
  2680.     if hasattr(f, 'url'):
  2681.         result['href'] = f.url
  2682.         result['status'] = 200
  2683.     if hasattr(f, 'status'):
  2684.         result['status'] = f.status
  2685.     if hasattr(f, 'headers'):
  2686.         result['headers'] = f.headers.dict
  2687.     if hasattr(f, 'close'):
  2688.         f.close()
  2689.  
  2690.     # there are four encodings to keep track of:
  2691.     # - http_encoding is the encoding declared in the Content-Type HTTP header
  2692.     # - xml_encoding is the encoding declared in the <?xml declaration
  2693.     # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data
  2694.     # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
  2695.     http_headers = result.get('headers', {})
  2696.     result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \
  2697.         _getCharacterEncoding(http_headers, data)
  2698.     if http_headers and (not acceptable_content_type):
  2699.         if http_headers.has_key('content-type'):
  2700.             bozo_message = '%s is not an XML media type' % http_headers['content-type']
  2701.         else:
  2702.             bozo_message = 'no Content-type specified'
  2703.         result['bozo'] = 1
  2704.         result['bozo_exception'] = NonXMLContentType(bozo_message)
  2705.         
  2706.     result['version'], data = _stripDoctype(data)
  2707.  
  2708.     baseuri = http_headers.get('content-location', result.get('href'))
  2709.     baselang = http_headers.get('content-language', None)
  2710.  
  2711.     # if server sent 304, we're done
  2712.     if result.get('status', 0) == 304:
  2713.         result['version'] = ''
  2714.         result['debug_message'] = 'The feed has not changed since you last checked, ' + \
  2715.             'so the server sent no data.  This is a feature, not a bug!'
  2716.         return result
  2717.  
  2718.     # if there was a problem downloading, we're done
  2719.     if not data:
  2720.         return result
  2721.  
  2722.     # determine character encoding
  2723.     use_strict_parser = 0
  2724.     known_encoding = 0
  2725.     tried_encodings = []
  2726.     # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
  2727.     for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding):
  2728.         if not proposed_encoding: continue
  2729.         if proposed_encoding in tried_encodings: continue
  2730.         tried_encodings.append(proposed_encoding)
  2731.         try:
  2732.             data = _toUTF8(data, proposed_encoding)
  2733.             known_encoding = use_strict_parser = 1
  2734.             break
  2735.         except:
  2736.             pass
  2737.     # if no luck and we have auto-detection library, try that
  2738.     if (not known_encoding) and chardet:
  2739.         try:
  2740.             proposed_encoding = chardet.detect(data)['encoding']
  2741.             if proposed_encoding and (proposed_encoding not in tried_encodings):
  2742.                 tried_encodings.append(proposed_encoding)
  2743.                 data = _toUTF8(data, proposed_encoding)
  2744.                 known_encoding = use_strict_parser = 1
  2745.         except:
  2746.             pass
  2747.     # if still no luck and we haven't tried utf-8 yet, try that
  2748.     if (not known_encoding) and ('utf-8' not in tried_encodings):
  2749.         try:
  2750.             proposed_encoding = 'utf-8'
  2751.             tried_encodings.append(proposed_encoding)
  2752.             data = _toUTF8(data, proposed_encoding)
  2753.             known_encoding = use_strict_parser = 1
  2754.         except:
  2755.             pass
  2756.     # if still no luck and we haven't tried windows-1252 yet, try that
  2757.     if (not known_encoding) and ('windows-1252' not in tried_encodings):
  2758.         try:
  2759.             proposed_encoding = 'windows-1252'
  2760.             tried_encodings.append(proposed_encoding)
  2761.             data = _toUTF8(data, proposed_encoding)
  2762.             known_encoding = use_strict_parser = 1
  2763.         except:
  2764.             pass
  2765.     # if still no luck, give up
  2766.     if not known_encoding:
  2767.         result['bozo'] = 1
  2768.         result['bozo_exception'] = CharacterEncodingUnknown( \
  2769.             'document encoding unknown, I tried ' + \
  2770.             '%s, %s, utf-8, and windows-1252 but nothing worked' % \
  2771.             (result['encoding'], xml_encoding))
  2772.         result['encoding'] = ''
  2773.     elif proposed_encoding != result['encoding']:
  2774.         result['bozo'] = 1
  2775.         result['bozo_exception'] = CharacterEncodingOverride( \
  2776.             'documented declared as %s, but parsed as %s' % \
  2777.             (result['encoding'], proposed_encoding))
  2778.         result['encoding'] = proposed_encoding
  2779.  
  2780.     if not _XML_AVAILABLE:
  2781.         use_strict_parser = 0
  2782.     if use_strict_parser:
  2783.         # initialize the SAX parser
  2784.         feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
  2785.         saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
  2786.         saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
  2787.         saxparser.setContentHandler(feedparser)
  2788.         saxparser.setErrorHandler(feedparser)
  2789.         source = xml.sax.xmlreader.InputSource()
  2790.         source.setByteStream(_StringIO(data))
  2791.         if hasattr(saxparser, '_ns_stack'):
  2792.             # work around bug in built-in SAX parser (doesn't recognize xml: namespace)
  2793.             # PyXML doesn't have this problem, and it doesn't have _ns_stack either
  2794.             saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
  2795.         try:
  2796.             saxparser.parse(source)
  2797.         except Exception, e:
  2798.             if _debug:
  2799.                 import traceback
  2800.                 traceback.print_stack()
  2801.                 traceback.print_exc()
  2802.                 sys.stderr.write('xml parsing failed\n')
  2803.             result['bozo'] = 1
  2804.             result['bozo_exception'] = feedparser.exc or e
  2805.             use_strict_parser = 0
  2806.     if not use_strict_parser:
  2807.         feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '')
  2808.         feedparser.feed(data)
  2809.     result['feed'] = feedparser.feeddata
  2810.     result['entries'] = feedparser.entries
  2811.     result['version'] = result['version'] or feedparser.version
  2812.     result['namespaces'] = feedparser.namespacesInUse
  2813.     return result
  2814.  
  2815. if __name__ == '__main__':
  2816.     if not sys.argv[1:]:
  2817.         print __doc__
  2818.         sys.exit(0)
  2819.     else:
  2820.         urls = sys.argv[1:]
  2821.     zopeCompatibilityHack()
  2822.     from pprint import pprint
  2823.     for url in urls:
  2824.         print url
  2825.         print
  2826.         result = parse(url)
  2827.         pprint(result)
  2828.         print
  2829.  
  2830. #REVISION HISTORY
  2831. #1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
  2832. #  added Simon Fell's test suite
  2833. #1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
  2834. #2.0 - 10/19/2002
  2835. #  JD - use inchannel to watch out for image and textinput elements which can
  2836. #  also contain title, link, and description elements
  2837. #  JD - check for isPermaLink='false' attribute on guid elements
  2838. #  JD - replaced openAnything with open_resource supporting ETag and
  2839. #  If-Modified-Since request headers
  2840. #  JD - parse now accepts etag, modified, agent, and referrer optional
  2841. #  arguments
  2842. #  JD - modified parse to return a dictionary instead of a tuple so that any
  2843. #  etag or modified information can be returned and cached by the caller
  2844. #2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
  2845. #  because of etag/modified, return the old etag/modified to the caller to
  2846. #  indicate why nothing is being returned
  2847. #2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
  2848. #  useless.  Fixes the problem JD was addressing by adding it.
  2849. #2.1 - 11/14/2002 - MAP - added gzip support
  2850. #2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
  2851. #  start_admingeneratoragent is an example of how to handle elements with
  2852. #  only attributes, no content.
  2853. #2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
  2854. #  also, make sure we send the User-Agent even if urllib2 isn't available.
  2855. #  Match any variation of backend.userland.com/rss namespace.
  2856. #2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
  2857. #2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
  2858. #  snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
  2859. #  project name
  2860. #2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
  2861. #  removed unnecessary urllib code -- urllib2 should always be available anyway;
  2862. #  return actual url, status, and full HTTP headers (as result['url'],
  2863. #  result['status'], and result['headers']) if parsing a remote feed over HTTP --
  2864. #  this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
  2865. #  added the latest namespace-of-the-week for RSS 2.0
  2866. #2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
  2867. #  User-Agent (otherwise urllib2 sends two, which confuses some servers)
  2868. #2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
  2869. #  inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
  2870. #2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
  2871. #  textInput, and also to return the character encoding (if specified)
  2872. #2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
  2873. #  nested divs within content (JohnD); fixed missing sys import (JohanS);
  2874. #  fixed regular expression to capture XML character encoding (Andrei);
  2875. #  added support for Atom 0.3-style links; fixed bug with textInput tracking;
  2876. #  added support for cloud (MartijnP); added support for multiple
  2877. #  category/dc:subject (MartijnP); normalize content model: 'description' gets
  2878. #  description (which can come from description, summary, or full content if no
  2879. #  description), 'content' gets dict of base/language/type/value (which can come
  2880. #  from content:encoded, xhtml:body, content, or fullitem);
  2881. #  fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
  2882. #  tracking; fixed bug tracking unknown tags; fixed bug tracking content when
  2883. #  <content> element is not in default namespace (like Pocketsoap feed);
  2884. #  resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
  2885. #  wfw:commentRSS; resolve relative URLs within embedded HTML markup in
  2886. #  description, xhtml:body, content, content:encoded, title, subtitle,
  2887. #  summary, info, tagline, and copyright; added support for pingback and
  2888. #  trackback namespaces
  2889. #2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
  2890. #  namespaces, as opposed to 2.6 when I said I did but didn't really;
  2891. #  sanitize HTML markup within some elements; added mxTidy support (if
  2892. #  installed) to tidy HTML markup within some elements; fixed indentation
  2893. #  bug in _parse_date (FazalM); use socket.setdefaulttimeout if available
  2894. #  (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
  2895. #  'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
  2896. #  'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
  2897. #  and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
  2898. #2.7.1 - 1/9/2004 - MAP - fixed bug handling " and '.  fixed memory
  2899. #  leak not closing url opener (JohnD); added dc:publisher support (MarekK);
  2900. #  added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
  2901. #2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in
  2902. #  encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL);
  2903. #  fixed relative URI processing for guid (skadz); added ICBM support; added
  2904. #  base64 support
  2905. #2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many
  2906. #  blogspot.com sites); added _debug variable
  2907. #2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing
  2908. #3.0b3 - 1/23/2004 - MAP - parse entire feed with real XML parser (if available);
  2909. #  added several new supported namespaces; fixed bug tracking naked markup in
  2910. #  description; added support for enclosure; added support for source; re-added
  2911. #  support for cloud which got dropped somehow; added support for expirationDate
  2912. #3.0b4 - 1/26/2004 - MAP - fixed xml:lang inheritance; fixed multiple bugs tracking
  2913. #  xml:base URI, one for documents that don't define one explicitly and one for
  2914. #  documents that define an outer and an inner xml:base that goes out of scope
  2915. #  before the end of the document
  2916. #3.0b5 - 1/26/2004 - MAP - fixed bug parsing multiple links at feed level
  2917. #3.0b6 - 1/27/2004 - MAP - added feed type and version detection, result['version']
  2918. #  will be one of SUPPORTED_VERSIONS.keys() or empty string if unrecognized;
  2919. #  added support for creativeCommons:license and cc:license; added support for
  2920. #  full Atom content model in title, tagline, info, copyright, summary; fixed bug
  2921. #  with gzip encoding (not always telling server we support it when we do)
  2922. #3.0b7 - 1/28/2004 - MAP - support Atom-style author element in author_detail
  2923. #  (dictionary of 'name', 'url', 'email'); map author to author_detail if author
  2924. #  contains name + email address
  2925. #3.0b8 - 1/28/2004 - MAP - added support for contributor
  2926. #3.0b9 - 1/29/2004 - MAP - fixed check for presence of dict function; added
  2927. #  support for summary
  2928. #3.0b10 - 1/31/2004 - MAP - incorporated ISO-8601 date parsing routines from
  2929. #  xml.util.iso8601
  2930. #3.0b11 - 2/2/2004 - MAP - added 'rights' to list of elements that can contain
  2931. #  dangerous markup; fiddled with decodeEntities (not right); liberalized
  2932. #  date parsing even further
  2933. #3.0b12 - 2/6/2004 - MAP - fiddled with decodeEntities (still not right);
  2934. #  added support to Atom 0.2 subtitle; added support for Atom content model
  2935. #  in copyright; better sanitizing of dangerous HTML elements with end tags
  2936. #  (script, frameset)
  2937. #3.0b13 - 2/8/2004 - MAP - better handling of empty HTML tags (br, hr, img,
  2938. #  etc.) in embedded markup, in either HTML or XHTML form (<br>, <br/>, <br />)
  2939. #3.0b14 - 2/8/2004 - MAP - fixed CDATA handling in non-wellformed feeds under
  2940. #  Python 2.1
  2941. #3.0b15 - 2/11/2004 - MAP - fixed bug resolving relative links in wfw:commentRSS;
  2942. #  fixed bug capturing author and contributor URL; fixed bug resolving relative
  2943. #  links in author and contributor URL; fixed bug resolvin relative links in
  2944. #  generator URL; added support for recognizing RSS 1.0; passed Simon Fell's
  2945. #  namespace tests, and included them permanently in the test suite with his
  2946. #  permission; fixed namespace handling under Python 2.1
  2947. #3.0b16 - 2/12/2004 - MAP - fixed support for RSS 0.90 (broken in b15)
  2948. #3.0b17 - 2/13/2004 - MAP - determine character encoding as per RFC 3023
  2949. #3.0b18 - 2/17/2004 - MAP - always map description to summary_detail (Andrei);
  2950. #  use libxml2 (if available)
  2951. #3.0b19 - 3/15/2004 - MAP - fixed bug exploding author information when author
  2952. #  name was in parentheses; removed ultra-problematic mxTidy support; patch to
  2953. #  workaround crash in PyXML/expat when encountering invalid entities
  2954. #  (MarkMoraes); support for textinput/textInput
  2955. #3.0b20 - 4/7/2004 - MAP - added CDF support
  2956. #3.0b21 - 4/14/2004 - MAP - added Hot RSS support
  2957. #3.0b22 - 4/19/2004 - MAP - changed 'channel' to 'feed', 'item' to 'entries' in
  2958. #  results dict; changed results dict to allow getting values with results.key
  2959. #  as well as results[key]; work around embedded illformed HTML with half
  2960. #  a DOCTYPE; work around malformed Content-Type header; if character encoding
  2961. #  is wrong, try several common ones before falling back to regexes (if this
  2962. #  works, bozo_exception is set to CharacterEncodingOverride); fixed character
  2963. #  encoding issues in BaseHTMLProcessor by tracking encoding and converting
  2964. #  from Unicode to raw strings before feeding data to sgmllib.SGMLParser;
  2965. #  convert each value in results to Unicode (if possible), even if using
  2966. #  regex-based parsing
  2967. #3.0b23 - 4/21/2004 - MAP - fixed UnicodeDecodeError for feeds that contain
  2968. #  high-bit characters in attributes in embedded HTML in description (thanks
  2969. #  Thijs van de Vossen); moved guid, date, and date_parsed to mapped keys in
  2970. #  FeedParserDict; tweaked FeedParserDict.has_key to return True if asking
  2971. #  about a mapped key
  2972. #3.0fc1 - 4/23/2004 - MAP - made results.entries[0].links[0] and
  2973. #  results.entries[0].enclosures[0] into FeedParserDict; fixed typo that could
  2974. #  cause the same encoding to be tried twice (even if it failed the first time);
  2975. #  fixed DOCTYPE stripping when DOCTYPE contained entity declarations;
  2976. #  better textinput and image tracking in illformed RSS 1.0 feeds
  2977. #3.0fc2 - 5/10/2004 - MAP - added and passed Sam's amp tests; added and passed
  2978. #  my blink tag tests
  2979. #3.0fc3 - 6/18/2004 - MAP - fixed bug in _changeEncodingDeclaration that
  2980. #  failed to parse utf-16 encoded feeds; made source into a FeedParserDict;
  2981. #  duplicate admin:generatorAgent/@rdf:resource in generator_detail.url;
  2982. #  added support for image; refactored parse() fallback logic to try other
  2983. #  encodings if SAX parsing fails (previously it would only try other encodings
  2984. #  if re-encoding failed); remove unichr madness in normalize_attrs now that
  2985. #  we're properly tracking encoding in and out of BaseHTMLProcessor; set
  2986. #  feed.language from root-level xml:lang; set entry.id from rdf:about;
  2987. #  send Accept header
  2988. #3.0 - 6/21/2004 - MAP - don't try iso-8859-1 (can't distinguish between
  2989. #  iso-8859-1 and windows-1252 anyway, and most incorrectly marked feeds are
  2990. #  windows-1252); fixed regression that could cause the same encoding to be
  2991. #  tried twice (even if it failed the first time)
  2992. #3.0.1 - 6/22/2004 - MAP - default to us-ascii for all text/* content types;
  2993. #  recover from malformed content-type header parameter with no equals sign
  2994. #  ('text/xml; charset:iso-8859-1')
  2995. #3.1 - 6/28/2004 - MAP - added and passed tests for converting HTML entities
  2996. #  to Unicode equivalents in illformed feeds (aaronsw); added and
  2997. #  passed tests for converting character entities to Unicode equivalents
  2998. #  in illformed feeds (aaronsw); test for valid parsers when setting
  2999. #  XML_AVAILABLE; make version and encoding available when server returns
  3000. #  a 304; add handlers parameter to pass arbitrary urllib2 handlers (like
  3001. #  digest auth or proxy support); add code to parse username/password
  3002. #  out of url and send as basic authentication; expose downloading-related
  3003. #  exceptions in bozo_exception (aaronsw); added __contains__ method to
  3004. #  FeedParserDict (aaronsw); added publisher_detail (aaronsw)
  3005. #3.2 - 7/3/2004 - MAP - use cjkcodecs and iconv_codec if available; always
  3006. #  convert feed to UTF-8 before passing to XML parser; completely revamped
  3007. #  logic for determining character encoding and attempting XML parsing
  3008. #  (much faster); increased default timeout to 20 seconds; test for presence
  3009. #  of Location header on redirects; added tests for many alternate character
  3010. #  encodings; support various EBCDIC encodings; support UTF-16BE and
  3011. #  UTF16-LE with or without a BOM; support UTF-8 with a BOM; support
  3012. #  UTF-32BE and UTF-32LE with or without a BOM; fixed crashing bug if no
  3013. #  XML parsers are available; added support for 'Content-encoding: deflate';
  3014. #  send blank 'Accept-encoding: ' header if neither gzip nor zlib modules
  3015. #  are available
  3016. #3.3 - 7/15/2004 - MAP - optimize EBCDIC to ASCII conversion; fix obscure
  3017. #  problem tracking xml:base and xml:lang if element declares it, child
  3018. #  doesn't, first grandchild redeclares it, and second grandchild doesn't;
  3019. #  refactored date parsing; defined public registerDateHandler so callers
  3020. #  can add support for additional date formats at runtime; added support
  3021. #  for OnBlog, Nate, MSSQL, Greek, and Hungarian dates (ytrewq1); added
  3022. #  zopeCompatibilityHack() which turns FeedParserDict into a regular
  3023. #  dictionary, required for Zope compatibility, and also makes command-
  3024. #  line debugging easier because pprint module formats real dictionaries
  3025. #  better than dictionary-like objects; added NonXMLContentType exception,
  3026. #  which is stored in bozo_exception when a feed is served with a non-XML
  3027. #  media type such as 'text/plain'; respect Content-Language as default
  3028. #  language if not xml:lang is present; cloud dict is now FeedParserDict;
  3029. #  generator dict is now FeedParserDict; better tracking of xml:lang,
  3030. #  including support for xml:lang='' to unset the current language;
  3031. #  recognize RSS 1.0 feeds even when RSS 1.0 namespace is not the default
  3032. #  namespace; don't overwrite final status on redirects (scenarios:
  3033. #  redirecting to a URL that returns 304, redirecting to a URL that
  3034. #  redirects to another URL with a different type of redirect); add
  3035. #  support for HTTP 303 redirects
  3036. #4.0 - MAP - support for relative URIs in xml:base attribute; fixed
  3037. #  encoding issue with mxTidy (phopkins); preliminary support for RFC 3229;
  3038. #  support for Atom 1.0; support for iTunes extensions; new 'tags' for
  3039. #  categories/keywords/etc. as array of dict
  3040. #  {'term': term, 'scheme': scheme, 'label': label} to match Atom 1.0
  3041. #  terminology; parse RFC 822-style dates with no time; lots of other
  3042. #  bug fixes
  3043. #4.1 - MAP - removed socket timeout; added support for chardet library
  3044.